Next Permutation
Last updated
Was this helpful?
Last updated
Was this helpful?
Array
Medium
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
The replacement must be and use only constant extra memory.
Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,3
→1,3,2
3,2,1
→1,2,3
1,1,5
→1,5,1
找规律题。
例子🌰 :
从右往左,找到第一个小于右边的数,也就是第一个不满足递增规律的数字,下标i
例子中是 2
在 (i, nums.length)范围内,寻找恰好比nums[i]
大的数,下标j
例子中是 3
交换i
, j
元素
例子中:交换2,3的位置
逆序[i + 1, nums.length)
的子数组(subarray)
例子结果结果:[1,3,0,2,4,5]
这个规律现场很难想出来,就当一个基本事实规律记住好了...不然这题应该是Hard难度。