码迷,mamicode.com
首页 > 其他好文 > 详细

31. Next Permutation (Array)

时间:2015-10-05 09:16:57      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:

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

思路:Array是无序的,但有规律可循。要交换的两个数,左边的那个总是比右边数小的数字中的最低位,右边的数是左边数右边的数字中比左边数大的最小的一个数;交换后递增排序左边数之后的数字

class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        int size = nums.size();
        if(size <= 1) return;
        
        int tmp, swapIndex = size;
        
        for(int lIndex = size-2; lIndex >= 0 ; lIndex--){ // to find the digit in the most right place whose value is smaller than a digit on its right
            for(int rIndex = lIndex+1; rIndex <size; rIndex++){ // to find the minimum digit who is larger than nums[lIndex]
                if(nums[lIndex] >= nums[rIndex]) continue;
                
                if(swapIndex == size){ //first find an eligible swap item
                    swapIndex = rIndex;
                }
                else if(nums[rIndex] < nums[swapIndex]){
                    swapIndex = rIndex;
                }
            }
            if(swapIndex != size){
                tmp = nums[lIndex];
                nums[lIndex] = nums[swapIndex];
                nums[swapIndex] = tmp;
                
                sort(nums.begin()+lIndex+1, nums.end());
                return;
            }
        }
        sort(nums.begin(), nums.end());
    }
};

 

31. Next Permutation (Array)

标签:

原文地址:http://www.cnblogs.com/qionglouyuyu/p/4855323.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!