LeetCode 31. Next Permutation

半秋L

关注

阅读 56

2023-09-05


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,31,1,5 → 1,5,1answer:

class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        int pre,end;
        end = nums.size() - 1;
        if(end == 0) return;
        pre = end - 1;
        int temp;
        bool find = false;
        while(pre >= 0){
            if(nums[pre] < nums[end]){
                int index = nums.size() - 1;
                while(index > pre && nums[index] <= nums[pre] ){
                    index --;
                }
                temp = nums[pre];
                nums[pre] = nums[index];
                nums[index] = temp;
                sort(nums.begin() + pre + 1,nums.end());
                find = true;
               break;
            }
            pre --;
            end --;
        }
        if(!find) sort(nums.begin(),nums.end());
        return ;
    }
};






精彩评论(0)

0 0 举报