首页 > 其他 > 详细

LintCode "Previous Permutation"

时间:2015-10-28 06:59:30      阅读:276      评论:0      收藏:0      [点我收藏+]

A reverse version of the Dictionary algorithm :) If you AC-ed "Next Permutation II", copy it over and just reverse the conditions.

class Solution {
public:
    /**
     * @param nums: An array of integers
     * @return: An array of integers that‘s previous permuation
     */
    vector<int> previousPermuation(vector<int> &num) {
        size_t len = num.size();
        if(len < 2) return num;
        
        // step 1: find first up-side from back
        int i = len - 1;
        while (i > 0)
        {
            if (num[i - 1] > num[i]) break;
            i--;
        }
        
        // step 2: find last num smaller than num[i-1]
        int j = i;
        while (j < len)
        {
            if (num[j] >= num[i - 1]) break;
            j++;
        }
        j--;
        
        // step 3: replace num[i-1] and num[j]
        if(i > 0)
            std::swap(num[i-1], num[j]);

        // step 4: reverse all after i
        std::reverse(num.begin() + i, num.end());
        return num;
    }
};

LintCode "Previous Permutation"

原文:http://www.cnblogs.com/tonix/p/4916200.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!