#31

Next Permutation

specialist · 970 · lc medium +32 · verified · 44.8% accepted · 21,232 likes · top 27%

play →

Description

Rearrange the elements of nums in-place to its next lexicographically greater permutation. If no such permutation exists, rearrange into the smallest (ascending) order. Use only constant extra memory.

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]

Code

1
2
3
4
5
6