zoukankan      html  css  js  c++  java
  • Java for LeetCode 031 Next Permutation

    Next Permutation

    Total Accepted: 33595 Total Submissions: 134095

     
     

    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.

    解题思路:

    题目不难,关键是理解题目的意思: 如果把nums看做一个数字的话,即返回比原来数大的最小的数(如果没有(原数是降序排列)则返回升序排列)。

    也就是字典排序,JAVA实现如下:

    	static public void nextPermutation(int[] nums) {
    		int index = nums.length - 1;
    		while (index >= 1) {
    			if (nums[index] > nums[index - 1]) {
    				int swapNum=nums[index-1],swapIndex = index+1;
    				while (swapIndex <= nums.length - 1&& swapNum < nums[swapIndex])
    					swapIndex++;
    				nums[index-1]=nums[swapIndex-1];
    				nums[swapIndex-1]=swapNum;
    				reverse(nums,index);
    				return;
    			}
    			index--;
    		}
    		reverse(nums,0);
    	}
    	static void reverse(int[] nums,int swapIndex){
    		int[] swap=new int[nums.length-swapIndex];
    		for(int i=0;i<swap.length;i++)
    			swap[i]=nums[nums.length-1-i];
    		for(int i=0;i<swap.length;i++)
    			nums[swapIndex+i]=swap[i];
    	}
    
  • 相关阅读:
    ValueStack、ActionContext
    s debug
    1923: [Sdoi2010]外星千足虫
    1013: [JSOI2008]球形空间产生器sphere
    HDU 3923 Invoker
    poj 1286 Necklace of Beads
    HDU 3037:Saving Beans
    2440: [中山市选2011]完全平方数
    1101: [POI2007]Zap
    1968: [Ahoi2005]COMMON 约数研究
  • 原文地址:https://www.cnblogs.com/tonyluis/p/4485612.html
Copyright © 2011-2022 走看看