• 31. Next Permutation (JAVA)


    Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.

    If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).

    The replacement must be in-place and use only constant extra memory.

    Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.

    1,2,3 → 1,3,2
    3,2,1 → 1,2,3
    1,1,5 → 1,5,1

     
    class Solution {
        public void nextPermutation(int[] nums) {
            int tmp;
            int i;
            int j;
            for(i = nums.length-2; i >= 0; i--){
                if(nums[i] < nums[i+1]) break;
            }
            
            if(i >= 0){
                //find the smallest num in the right which is larger than num[i]
                for(j = nums.length-1; j >= i; j--){
                    if(nums[j] > nums[i]) break;
                }
                
                //swap these two num
                tmp = nums[i];
                nums[i] = nums[j];
                nums[j] = tmp;
                
                //sort
                Arrays.sort(nums, i+1, nums.length);
            }
            else{
                Arrays.sort(nums);
            }
        }
    
    }

    寻找规律:

    - 从右向左扫描,找到小于右侧数字的第一个数字

    - 将右侧大于它的最小的那个数放在该位,它和其余右侧的数字从小到大排列放在右侧。

  • 相关阅读:
    python学习之字典合并
    python学习之列表、元组、集合、字典随笔
    图像检索中的概念
    卷积、反卷积、转置卷积资源
    计算机视觉顶级会议和期刊
    Week17
    Python协程资源
    深度图像资源
    Geo-localization论文阅读list2
    NetVLAD原理详解和推导
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/10797450.html
Copyright © 2020-2023  润新知