题解 | #牛群的编号重排#
牛群的编号重排
https://www.nowcoder.com/practice/220a216469c14a52b4eb6709e041feb1
题目考察的知识点: 排序
题目解答方法的文字分析:
从后往前遍历,找到第一个非递减的位置,此时即下一个小字典的修改项,将该值与前一个交换,在对后面的值倒序排序即可,因为后面的值都是递减的,排序后为递增
本题解析所用的编程语言:Java
完整且正确的编程代码
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param cows int整型一维数组
* @return int整型一维数组
*/
public int[] nextPermutation (int[] cows) {
// write code here
int up = cows.length-1;
while(up>=1 && cows[up]>=cows[up-1]){
up--;
}
if(up == 0){
return reverse(cows,0,cows.length-1);
}
int temp = cows[up];
cows[up] = cows[up-1];
cows[up-1] = temp;
return reverse(cows,up,cows.length-1);
}
private int[] reverse(int[] cows,int start,int end){
int temp;
while(start<end){
temp = cows[start];
cows[start] = cows[end];
cows[end] = temp;
start++;
end--;
}
return cows;
}
}