Tuesday, March 31, 2015

LeetCode [31] Next Permutation

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





 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        int n = nums.size();
        if(n<=1) return;

        //find the first decreasing position from the end;
        int i=n-2;
        while(i>=0 && nums[i]>=nums[i+1]) i--;
        
        //this is the greatest number. return the smallest number;
        if(i<0)
        {
            sort(nums.begin(), nums.end());
            return;
        }

        //find the smallest number (from the end) greater than nums[i]
        int j=n-1;
        while(j>i && nums[j]<=nums[i]) j--;
        swap(nums[i], nums[j]);
        sort(nums.begin()+i+1, nums.end());
    }
};

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
    public void nextPermutation(int[] nums) {
        int n = nums.length;

        int i = n-2;
        for(; i>=0; --i){
            if(nums[i]<nums[i+1]) break;
        }
        
        if(i<0){
            Arrays.sort(nums);
            return;
        }
        
        int j = n-1;
        for(; j>i; --j){
            if(nums[j]>nums[i]) break;
        }
        
        //swap i and j
        int t = nums[i];
        nums[i] = nums[j];
        nums[j] = t;
        Arrays.sort(nums,i+1,n);
    }
}

No comments:

Post a Comment