[LeetCode] 31. Next Permutation_Medium tag: sort, two pointers
2021-08-07 23:37 Johnson_强生仔仔 阅读(21) 评论(0) 编辑 收藏 举报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.
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]
Constraints:
1 <= nums.length <= 100
0 <= nums[i] <= 100
Ideas:
1. 先建两个helper function,一个swap另一个来reverse
2. 从后面往前面找nums[i] <nums[i + 1], 那么这个i就是需要更换的index
3. 再从[i + 1, n - 1]这个range里面从后面往前找 nums[index] > nums[i]的,也就是说last index > nums[i]的
4. 把2得到的i 和 3得到的index来swap, 这个时候i 后面的排序还是降序并且没有变
5. 再把i后面的reverse,因为之前是降序,比较大,所以reverse换成最小的
Code:
class Solution: def nextPermutation(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ n = len(nums) if n == 1: return i = n - 2 while i >= 0 and nums[i] >= nums[i + 1]: i -= 1 if i >= 0: last_bigger = n - 1 while nums[last_bigger] <= nums[i]: last_bigger -= 1 self.swap(nums, i, last_bigger) self.reverse(nums, i + 1, n - 1) def swap(self, nums, index1, index2): nums[index1], nums[index2] = nums[index2], nums[index1] def reverse(self, nums, start, end): while start < end: self.swap(nums, start, end) start += 1 end -= 1