题解 | #牛群的编号重排#
牛群的编号重排
https://www.nowcoder.com/practice/220a216469c14a52b4eb6709e041feb1
知识点
数组
解题思路
以1,5,2,3,7举例。
1.从右到左找到非递减的数,5,如果没有找到直接就进入了步骤3
2.从5开始从左到右找到非递增的数,7。交换5和7之前的数3,此时数组为1,3,2,5,7。
3.反正3之后的数组,结果数组为1,3,7,5,2.
Java题解
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param cows int整型一维数组
* @return int整型一维数组
*/
public int[] nextPermutation (int[] cows) {
// write code here
int n = cows.length;
int index = n - 2;
while(index >= 0 && cows[index] <= cows[index + 1]){
index --;
}
int tempIndex = index;
if(index >= 0){ //找到非递减的数
int num = cows[index++];
while(index < n && cows[index] <= num){
index++;
}
cows[tempIndex] = cows[index - 1];
cows[index - 1] = num;
}
tempIndex ++;
int right = n - 1;
while(tempIndex < right){
int temp = cows[tempIndex];
cows[tempIndex++] = cows[right];
cows[right--] = temp;
}
return cows;
}
}

联想公司福利 1500人发布