31. Next Permutation

1. Description

Implement 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.

2. Example

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

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

Example 3:
Input: nums = [1,1,5]
Output: [1,5,1]

Example 4:
Input: nums = [1]
Output: [1]

3. Constraints

  • 1 <= nums.length <= 100
  • 0 <= nums[i] <= 100

4. Solutions

My Accepted Solution

n = m_nums.size()
Time complexity: O(n)
Space complexity: O(1)

class Solution {
public:
    void nextPermutation(vector<int>& m_nums) {
        int last_reverse_index = m_nums.size() - 1;
        for(; last_reverse_index >= 0; --last_reverse_index) {
            if(last_reverse_index == 0) {
                sort(m_nums.begin(), m_nums.end());
                return ;
            } else if(m_nums[last_reverse_index] > m_nums[last_reverse_index - 1]){
                break;
            }
        }

        int exchange_index = last_reverse_index - 1;
        int min_larger_value_index = last_reverse_index;
        for(; min_larger_value_index < m_nums.size(); ++min_larger_value_index) {
            if(m_nums[min_larger_value_index] <= m_nums[exchange_index]) {
                break;
            }
        }

        swap(m_nums[exchange_index], m_nums[min_larger_value_index - 1]);
        sort(m_nums.begin() + last_reverse_index, m_nums.end());
    }
};
Last updated:
Tags: Array
comments powered by Disqus