c++ O(n) solution


  • 0
    H
    class Solution {
    public:
        void nextPermutation(vector<int>& nums) {
            int k = -1, t = -1, n = nums.size();
            for(int i = n - 2; i >= 0; i --)
                if(nums[i] < nums[i+1]) {
                    k = i;
                    break;
                }
            if(k == -1) {
                reverse(nums.begin(), nums.end());
                return;
            }
            for(int i = n - 1; i > k; i --)
                if(nums[i] > nums[k]) {
                    t = i;
                    break;
                }
            swap(nums[k], nums[t]);
            reverse(nums.begin() + k + 1, nums.end());
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.