LeetCode第31题:下一个排列

僤鯓⒐⒋嵵緔 提交于 2019-12-16 01:58:34

LeetCode第31题:下一个排列

  • 题目:实现获取下一个排列的函数,算法需要将给定数字序列重新排列成字典序中下一个更大的排列。如果不存在下一个更大的排列,则将数字重新排列成最小的排列(即升序排列)。必须原地修改,只允许使用额外常数空间。
  • 解法一:生病了,先写到这吧。有了点想法,有时间再改
class Solution {
    public void nextPermutation(int[] nums) {
        
        int len=nums.length;
        int ay[]=new int[len];
        int R=len-1,L=R-1;
        while(L>=0){
            if(nums[L]>nums[R]){
                if(R==1){
                    Arrays.sort(nums);
                    break;
                }
                L--;
            }else{
                int a=nums[L];
                nums[L]=nums[R];
                nums[R]=a;
                if((len==3) || len==2){
                    break;
                }
                if(len==3 && L==0){
                    a=nums[1];
                    nums[1]=nums[2];
                    nums[2]=a;
                    break;
                }
                for(int i=L+1,j=0;i<len;i++,j++){
                    ay[j]=nums[i];
                }
                Arrays.sort(ay);
                for(int i=L+2,j=0;i<len;i++,j++){
                    nums[i]=ay[j];
                    //System.out.println(ay[j]);
                }
                break;
            }
            if(L<0 && R!=0){
                R--;
                L=R-1;
            }
        }
        for(int i=0;i<len;i++){
            System.out.println(nums[i]);
        }
    }
}
  • 解法二:先找到一个最长递减子序列,把它逆序,这是最小序列。我们只需要在最小的序列中找一个比它大并且最接近它的元素,将它换掉就可以了(替换并没有破坏最小序列的单调性),这样整个序列就是我们的目标序列。

作者:97wgl
链接:https://leetcode-cn.com/problems/next-permutation/solution/xia-yi-ge-pai-lie-on-si-lu-jian-dan-by-97wgl/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

class Solution {
    public void nextPermutation(int[] nums) {
        for (int i = nums.length - 1; i >= 0; i--) {
            if (i == 0) {
                reverse(nums, 0, nums.length - 1);
                return;
            }
            if (nums[i] > nums[i - 1]) {
                // 将递增序列逆序
                reverse(nums, i, nums.length - 1);
                for (int j = i; j < nums.length; j++) {
                    if (nums[j] > nums[i - 1]) {
                        swap(nums, j, i - 1);
                        return;
                    }
                }
            }
        }
    }

    // 数组反转 
    private void reverse(int[] nums, int begin, int end) {
        while (begin < end) {
            swap(nums, begin++, end--);
        }
    }

    // 交换
    private void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}

作者:97wgl
链接:https://leetcode-cn.com/problems/next-permutation/solution/xia-yi-ge-pai-lie-on-si-lu-jian-dan-by-97wgl/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!