Posted on

Description

Submission

class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        if(nums.size() <= 2) {
            reverse(nums.begin(), nums.end());
            return;
        }
        int min_index  = nums.size() - 1;
        int i = nums.size() - 2;
        for(; i >= 0; --i) {
            if(nums[i] < nums[i + 1]) {
                int justLargerIndex = i + 1;
                for(int j = i + 1; j < nums.size(); ++j) {
                    if(nums[justLargerIndex] > nums[j] && nums[j] > nums[i])
                        justLargerIndex = j;
                }
                swap(nums[i], nums[justLargerIndex]);
                sort(nums.begin() + i + 1, nums.end());
                return;
            } else if(i == 0) {
                reverse(nums.begin(), nums.end()); 
                return;
            }
        }
        
    }
};

Submission 210417

class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        
        int n = nums.size();
        int ptr = n - 1;
        int t = n - 1;
        for(; ptr >= 1; --ptr) {
            if(nums[ptr] > nums[t]) t = ptr;
            if(nums[ptr] > nums[ptr-1]) break;
        }


        if(ptr == 0) {
            reverse(nums.begin(), nums.end());
            return;
        }
        // find the one just bigger than nums[ptr-1]
        for(int i = ptr; i < n; ++i) {
            if(nums[i] > nums[ptr-1] && nums[i] < nums[t]) {
                t = i;
            }
        }

        swap(nums[ptr-1], nums[t]);
        sort(nums.begin()+ptr, nums.end());
    }
};

Leave a Reply

Your email address will not be published. Required fields are marked *