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, do not allocate 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

 

 解题思路图解:
LeetCode 31 - Next Permutation_第1张图片
 上图引用自:http://fisherlei.blogspot.com/2012/12/leetcode-next-permutation.html

 

public class Solution {
    public void nextPermutation(int[] num) {
        if(num == null || num.length <= 1) return;
        int i = num.length-1;
        for(; i>0; i--) {
            if(num[i] > num[i-1]) {
                //2543222111, 1511, 3521, 132, 231
                int k = num.length-1;  
                while(num[k]<=num[i-1]) {
                    k--;
                }
                swap(num, k, i-1);
                break;
            }
        }
        int j = num.length-1;
        while(i<j) {
            swap(num, i++, j--);
        }
    }
    
    private void swap(int[] num, int i, int j) {
        int tmp = num[i];
        num[i] = num[j];
        num[j] = tmp;
    }
}

 

C++的版本更加简洁:

void nextPermutation(vector<int>& nums) {
    int n = nums.size();
    if(n <= 1) return;
    int i = n-1;
    for(; i>0; i--) {
        if(nums[i]>nums[i-1]) {
            int j = n-1;
            while(nums[j] <= nums[i-1]) j--;
            swap(nums[i-1], nums[j]);
            break;
        }
    }
    reverse(nums.begin()+i, nums.end());
}

 

你可能感兴趣的:(LeetCode,next,permutation)