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, do not allocate 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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
void nextPermutation(vector<int>& nums) { | |
//Scan from right to left | |
//Detect first pair of number (N_t, N_t-1) that N_t<N_t-1 | |
//On the right side of N_t-1, find the smallest number N* that is larger than N_t | |
//Switch N* and N_t | |
//Sort all numbers on the right side of N*. | |
int len=nums.size(); | |
// Find pair | |
int i=len-1; | |
for(i=len-1; i>=0; i--){ | |
if(nums[i]>nums[i-1]&&i>0) | |
break; | |
} | |
if(i<=0){ | |
reverse(nums.begin(), nums.end()); | |
return; | |
} | |
//Find N* | |
int j=i; | |
int minmax=nums[i]; | |
int idx=i; | |
for(j=i; j<nums.size(); ++j){ | |
if(nums[j]>nums[i-1]&&nums[j]<=minmax){ | |
minmax=nums[j]; | |
idx=j; | |
} | |
} | |
//Switch N_t-1, N* | |
swap(nums[i-1], nums[idx]); | |
//Sort all numbers on the right side of N* | |
if(i!=nums.size()-1) | |
reverse(nums.begin()+i, nums.end()); | |
return; | |
} | |
}; |
No comments:
Post a Comment