LeetCode 31 数组的下一个排列

 

class Solution {
public:
    void nextPermutation(vector& nums) {
        int i = nums.size() - 2;
        while(i >= 0 && nums[i+1] <= nums[i]) {
            i--;
        }
        if(i >= 0) {
            int j = nums.size() - 1;
            while(j >= 0 && nums[j] <= nums[i]) j--;
            swap(nums, i, j);
        }
        reverse(nums, i+1); //把i之后的降序全部转换成升序
    }

    void reverse(vector& nums, int start) {
        int i = start, j = nums.size()-1;
        while(i < j) {
            swap(nums, i, j);
            i++;
            j--;
        }
    }

    void swap(vector& nums, int i, int j) {
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }
};

 

你可能感兴趣的:(LeetCode,数组)