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

Leetcode:Next Permutation 下一个排列

时间:2014-06-22 23:35:19      阅读:262      评论:0      收藏:0      [点我收藏+]

标签:style   class   blog   code   ext   color   

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,31,3,2
3,2,11,2,3
1,1,51,5,1

 

解题分析:

step1. 从后往前遍历,找到第一个 升序的相邻元素,即 num.at(i) < num.at(i+1)

          如果遍历之后 i的值为-1,即 数组中所有相邻都逆序,即数组降序,此时只需要 reverse数组,直接返回即可

step2. 再次从后往前遍历,找到第一个 num.at(k) > num.at(i) 的值

          如果 step1没有全逆序直接返回,那么这一步的 k值一定 大于 i,因为存在相邻的升序对

step3. swap(num.at(i), num.at(k))

step4. 将 num位于 坐标 i 以后的元素反转

class Solution {
public:
    void nextPermutation(vector<int> &num) {
        if (num.size() < 2) return;
        int i = 0;
        int k = 0;
        for (i = num.size() - 2; i >= 0; --i) {
            if (num.at(i) < num.at(i+1)) {
                break;
            }
        }
        if (i < 0) {
            reverse(num.begin() + i + 1, num.end());
            return;
        }
        
        for (k = num.size() - 1; k > i; --k) {
            if (num.at(k) > num.at(i)) {
                break;
            }
        }
        swap(num.at(i), num.at(k));
        reverse(num.begin() + i + 1, num.end());
    }
};

 

Leetcode:Next Permutation 下一个排列,布布扣,bubuko.com

Leetcode:Next Permutation 下一个排列

标签:style   class   blog   code   ext   color   

原文地址:http://www.cnblogs.com/wwwjieo0/p/3800110.html

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