0
点赞
收藏
分享

微信扫一扫

31. Next Permutation

Python芸芸 2022-12-01 阅读 64


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​


​​Subscribe​​ to see which companies asked this question

参见以前的 

lintcode:Next Permutation


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


举报

相关推荐

0 条评论