Next Permutation

Implement the next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.

If such an arrangement is not possible, it must rearrange it as the lowest possible order (i.e., sorted in ascending order).

The replacement must be in place and use only constant extra memory.

Example:

Input: nums = [1,2,3]
Output: [1,3,2]

Approach:

C++

#include <bits/stdc++.h>
using namespace std;

void nextPermutation(vector<int&nums)
{
    int index = -1;
    int n = nums.size();

    for (int i = n - 2i >= 0i--)
    {
        if (nums[i] < nums[i + 1])
        {
            index = i;
            break;
        }
    }
    if (index != -1)
    {
        for (int i = n - 1i >= 0i--)
        {
            if (nums[i] > nums[index])
            {
                swap(nums[i]nums[index]);
                break;
            }
        }
    }
    index++;
    int j = n - 1;

    while (index < j)
    {
        swap(nums[index]nums[j]);
        j--;
        index++;
    }

    return;
}

int main()
{
    vector<intnums = {123};

    nextPermutation(nums);

    cout << "[";
    for (int i = 0i < nums.size(); i++)
    {
        cout << nums[i];
        if (i != nums.size() - 1)
            cout << ",";
    }
    cout << "]";

    return 0;
}


No comments:

Post a Comment