题解 | #牛群的编号重排#

牛群的编号重排

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;
    }
}
全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务