zoukankan      html  css  js  c++  java
  • #Leetcode# 31. Next Permutation

    https://leetcode.com/problems/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 and use only constant 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>& nums) {
            int n = nums.size();
            int temp1, temp2;
            for(int i = n - 2; i >= 0; i --) {
                if(nums[i + 1] > nums[i]) {
                    temp1 = i;
                    for(int j = n - 1; j > temp1; j --) {
                        if(nums[j] > nums[i]) {
                            temp2 = j;
                            break;
                        }
                    }
                    swap(nums[temp1], nums[temp2]);
                    reverse(nums.begin() + i + 1, nums.end());
                    return ;
                }
            }
            reverse(nums.begin(), nums.end());
        }
    };
    

     从后向前找到第一个后面数字比前面小的位置 然后确定这个位置 再从后向前找出第一个比该数字大的位置 然后交换着两个数字 然后这两个数字之后对应的部分也要逆序 用到 $reverse$ 函数进行反转  做法  get!!!

  • 相关阅读:
    fs.readdirSync
    symbol
    vuex-count
    webpack2.0
    关于vuex报错
    store
    .NET MVC 验证码
    SQLServer 加密
    IE10、IE11下SCRIPT5009: “__doPostBack”未定义
    Sql Server 增加字段、修改字段、修改类型、修改默认值
  • 原文地址:https://www.cnblogs.com/zlrrrr/p/10009470.html
Copyright © 2011-2022 走看看