首页 > 编程语言 > 详细

Java for LeetCode 031 Next Permutation

时间:2015-05-07 18:38:45      阅读:264      评论:0      收藏:0      [点我收藏+]

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];
	}

 

Java for LeetCode 031 Next Permutation

原文:http://www.cnblogs.com/tonyluis/p/4485612.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!