LeetCode: Next Permutation

来源:互联网 发布:乐器声音模拟软件 编辑:程序博客网 时间:2024/06/02 05:17

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*

解题过程 :
对于这个问题,我看到有人使用全排列做的,先把所有情况排列出来,再排序,这样略复杂,当然也可以不用。看了一个博主的思路,觉得很可行,时间复杂度为O(n),空间复杂度为O(1):
1) 先从后往前找到第一个不是依次增长的数,记录下位置p。比如例子中的3,对应的位置是1;
2) 接下来分两种情况:
(1) 如果上面的数字都是依次增长的,那么说明这是最后一个排列,下一个就是第一个,其实把所有数字反转过来即可(比如(6,5,4,3,2,1)下一个是(1,2,3,4,5,6));
(2) 否则,如果p存在,则从后往前查找第一个大于位置p的数,然后两个调换位置,比如例子中的4。调换位置后得到(2,4,6,5,3,1)。最后把p之后的所有数字倒序,比如例子中得到(2,4,1,3,5,6), 这个即是要求的下一个排列。因为p之后的数是按从大到小排列的,所以直接用sort函数从小到大排序就是他们的倒序了。

   void nextPermutation(vector<int>& nums) {        if(nums.size() == 0) return ;        if(nums.size() == 1) return ;        int length = nums.size()-1;        int i = length-1;        while(i>-1 && nums[i] > nums[i+1]) {            i--;        }         if(i>=0){            int j = length;            while(nums[j]<=nums[i]){                j--;            }             int temp = nums[i];            nums[i] = nums[j];            nums[j] = temp;        }    //  cout<<i;            sort(nums.begin()+i+1,nums.end());        return;    }       
0 0
原创粉丝点击