zoukankan      html  css  js  c++  java
  • LintCode "Previous Permutation"

    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;
        }
    };
  • 相关阅读:
    南阳97
    南阳96
    南阳94
    南阳77
    南阳75
    南阳74
    南阳65
    一般图匹配
    466E
    hdu5057 分块处理,当数值大于数据范围时树状数组 真是巧 将大数据分为小数据来处理
  • 原文地址:https://www.cnblogs.com/tonix/p/4916200.html
Copyright © 2011-2022 走看看