# Rockwall

### Blog Stats

• Posts - 29
• Stories - 1
• Comments - 0
• Trackbacks - 0

## LeetCode 【31. Next Permutation】

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

1.找到nums[i] > nums[i-1]

2.找出i-nums.size()-1之间比nums[i-1]大的最小值，交换这个值与nums[i-1]

3.对i-1到nums.size()-1之间的元素进行排序

class Solution {
public:
void nextPermutation(vector<int>& nums) {
int end = nums.size()-1;
while( end > 0 ){
if( nums[end] > nums[end-1] ){
break;
}
else{
end--;
}
}
if( end == 0 ){
sort(nums.begin(),nums.end());
}
else{
int min = nums[end];
int index = end;
for( int i = nums.size()-1; i > end; i-- ){
if( nums[i] < min && nums[i] > nums[end-1] ){
min = nums[i];
index = i;
}
}
swap(nums[index],nums[end-1]);
sort(nums.begin()+end,nums.end());
}
}
};


posted on 2016-08-11 19:56 Rockwall 阅读(...) 评论(...) 编辑 收藏