zoukankan      html  css  js  c++  java
  • leetcode problem 31 -- 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

    代码:

    class Solution {
    public:
        void nextPermutation(vector<int> &v) {
            int left = findIncFromRight(v);
            if (left != -1) {
                int right = findMinGreater(v, left); 
                swap(v[left], v[right]);
            }
            reverse(v.begin() + left + 1, v.end());
        }
    
    private:
        int findIncFromRight(vector<int> &v) {
            int i;
            for (i = v.size()-1; i > 0; --i) {
                if (v[i-1] < v[i])
                    break;
            }
            return i - 1;
        }
    
        int findMinGreater(vector<int>& v, int left) {
            int i; 
            for (i = left+1; i < v.size(); ++i) {
                if (v[left] >= v[i])
                    break;
            }
            return i-1;
        }
    };
  • 相关阅读:
    开通博客
    简单、方便、实用的日志记录系统
    浅谈近两年工作
    前端构建神器之 gulp
    CSS 3 transition属性
    angular.extend相关知识
    angular.element相关知识
    angularJS之$apply()方法
    Jquery选择器
    Jquery选择器小节
  • 原文地址:https://www.cnblogs.com/lysuns/p/4442015.html
Copyright © 2011-2022 走看看