Problem
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 in-place 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
Solution
Find the last acceding element x, swap with the smallest number y, y is after x that and y is greater than x.
Reverse the elements after x.
Time complexity: O(n)
Space complexity: O(1)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
// Author: Huahua, 8 ms class Solution { public: void nextPermutation(vector<int>& nums) { int i = nums.size() - 2; while (i >= 0 && nums[i + 1] <= nums[i]) --i; if (i >= 0) { int j = nums.size() - 1; while (j >= 0 && nums[j] <= nums[i]) --j; swap(nums[i], nums[j]); } reverse(begin(nums) + i + 1, end(nums)); } }; |
Python3
1 2 3 4 5 6 7 8 9 10 11 |
# Author: Huahua, 48 ms class Solution: def nextPermutation(self, nums): n = len(nums) i = n - 2 while i >= 0 and nums[i] >= nums[i + 1]: i -= 1 if i >= 0: j = n - 1 while j >= 0 and nums[j] <= nums[i]: j -= 1 nums[i], nums[j] = nums[j], nums[i] nums[i + 1:] = nums[i+1:][::-1] |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment