标签:leetcode
ARRAY;
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
首先找到:: 需要交换的元素i,j。然后交换。 之后进行reverse。
其中::1,2,3.最后一个升序的,2,3将其交换就好
如 其他的,抓住最后一个升序的,
最后一个升序的小技巧,找到比后面小的数,然后找到最后一个大的数字。
class Solution { public: void reversePart(vector<int>& nums,int k) { int j=nums.size()-1; int i=k+1; while(i<=j) { swap(nums[i],nums[j]); i++; j--; } } void nextPermutation(vector<int>& nums) { int flag=0; if(nums.size()==1) return; //find j int i=nums.size()-1; while (i>0&&nums[i-1]>=nums[i])//after is bigger. { i--; } int j=i; //difficult for me. while(j<nums.size()&&nums[j]>nums[i-1])j++; if(i==0) reversePart(nums,-1); else { swap(nums[i-1],nums[j-1]); reversePart(nums,i-1); } } };
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:leetcode
原文地址:http://blog.csdn.net/q286989429/article/details/47441481