zoukankan      html  css  js  c++  java
  • [leedcode 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

    public class Solution {
        public void nextPermutation(int[] nums) {
            //本题的难点是如何找到下一个Permutation 
            //阅读资料可知,^牢记这个形状,首先找到最大的i,并且满足nums[i]<nums[i+1]
            //再从后向前找到第一个nums[i]<nums[k],k>i
            //swap() i和k
            //反转i+1到n
            //注意递减序列的判断
            if(nums.length<=1) return;
            int len=nums.length-1;
            int i=0;
            for(i=len-1;i>=0;i--){
                if(nums[i]<nums[i+1])
                   break;
            }
            if(i<0){//注意判断是否是递减数列
                reverse(nums,0,len);
                return;
            }
            int k=len;
            for(;k>i;k--){
                if(nums[i]<nums[k])
                break;
            }
            swap(nums,k,i);
            reverse(nums,i+1,len);
        }
        public void reverse(int nums[],int i,int j){
            while(i<j){
                swap(nums,i,j);
                i++;j--;
            }
            
        }
        public void swap(int nums[],int i,int j){
                int temp=nums[i];
                nums[i]=nums[j];
                nums[j]=temp;
        }
    }
  • 相关阅读:
    HTTP request smuggling
    Do you really know CSS linear-gradients?
    Populating the page: how browsers work
    船舶智能管理系统API文档
    DocGuarder
    BUC LNB 器件
    BUC 与 LNB 的区别
    EIRP G/T 的意义
    语音的频率、频率分辨率、采样频率、采样点数、量化、增益
    机械波、电磁波的异同
  • 原文地址:https://www.cnblogs.com/qiaomu/p/4633437.html
Copyright © 2011-2022 走看看