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
时间:
2015年07月01日
思路
从低位往高位遍历,找到第一个比相邻的低位小的位index; 将”找到的该位index“与“从低位到高位第一个比该位大的位“交换;index位及更高位不用改变,低位部分是递增的顺序,现在改为递减的顺序即可。
注意
- C++里vector的用法。包括vector<>::iterator reverse_iterator; begin() end() rbegin() rend();*it 、++it等
- G++编译器存在的限制。不能在for循环里定义两个以上变量(?),所以最好把所有变量都在循环外定义。
代码:
class Solution {
public:
void nextPermutation(vector<int>& nums) {
int length = nums.size();
if(length == 0 || length == 1) return;
vector<int>::reverse_iterator index = nums.rend();
vector<int>::reverse_iterator r_it;
vector<int>::iterator it;
for( r_it = nums.rbegin() + 1; r_it != nums.rend(); ++r_it){
if(*r_it < *(r_it-1)){
index = r_it;
break;
}
}
if(index == nums.rend()){ //nums itself is the biggest //swap
for( it = nums.begin(),r_it = nums.rbegin();
it != nums.begin()+length/2; ++it,++r_it){
int temp = *r_it;
*r_it = *it;
*it = temp;
}
}
else{
for(r_it = nums.rbegin(); r_it != index; ++r_it){ //swap
if(*r_it > *index){
int temp = *index;
*index = *r_it;
*r_it = temp;
break;
}
}
//swap
for(int i = 0; i < (index-nums.rbegin())/2; ++i){
int temp = *(nums.rbegin()+i);
*(nums.rbegin()+i) = *(index - 1 - i);
*(index - 1 - i) = temp;
}
}
}
};
总结:
一直没怎么刷过题,今天打开leetcode pick one,没想到就是前天去宜信面试时的第一道题。
刷题很有用啊,面试官也是刷过题的,所以出的题也很可能就是这些题。