美文网首页
Next Permutation

Next Permutation

作者: BLUE_fdf9 | 来源:发表于2018-09-21 06:32 被阅读0次

    题目
    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,31,3,2
    3,2,11,2,3
    1,1,51,5,1

    答案

    class Solution {
        public void swap(int[] nums, int i, int j) {
            int t = nums[i];
            nums[i] = nums[j];
            nums[j] = t;
        }
        public void reverse(int[] nums, int l, int r) {
            while(l < r) swap(nums, l++, r--);
        }
        
        public void nextPermutation(int[] nums) {
            int n = nums.length;
            int p = -1, c = -1;
            for(int i = n - 1; i > 0; i--) {
                if(nums[i] > nums[i - 1]) {
                    p = i - 1;
                    break;
                }
            }
            if(p == -1) {
                reverse(nums, 0, nums.length - 1);
                return;
            }
            for(int i = n - 1; i > p; i--) {
                if(nums[i] > nums[p]) {
                    c = i;
                    break;
                }
            }
            swap(nums, p, c);
            reverse(nums, p + 1, nums.length - 1);
        }
    }
    

    相关文章

      网友评论

          本文标题:Next Permutation

          本文链接:https://www.haomeiwen.com/subject/bdgonftx.html