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
题目大意:
寻找给定数组的下一个排列组合,该排列组合最接近给定数组。
解法:
寻找下一个排列组合,一定是交换数组后半部分的数字,才能做到最接近原数组。先找到数组后半部分第一次出现的递增数对,从该数字往后才能出现递增序列。再从数组后面开始寻找第一个比该数字大的位置,该位置的数字一定是最接近该数字的。将这两个位置的数字进行交换,再对该数字后面的数组进行排序,就可以得到下一个排列组合。
C++:
class Solution { public: void nextPermutation(vector<int>& nums) { int n=nums.size(),k,l; for(k=n-2;k>=0;k--){ if(nums[k]<nums[k+1]) break; } if(k<0){ reverse(nums.begin(),nums.end()); }else{ for(l=n-1;l>=0;l--){ if(nums[l]>nums[k]) break; } swap(nums[l],nums[k]); reverse(nums.begin()+k+1,nums.end()); } } };
Python:
class Solution(object): def nextPermutation(self, nums): """ :type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead. """ if not nums: return None i=len(nums)-2 while i>=0: if nums[i]<nums[i+1]:break i-=1 if i<0: nums.sort() return j=len(nums)-1 while j>=0: if nums[j]>nums[i]: nums[i],nums[j]=nums[j],nums[i] nums[i+1:]=sorted(nums[i+1:]) return j-=1