码迷,mamicode.com
首页 > 编程语言 > 详细

Java for LeetCode 031 Next Permutation

时间:2015-05-07 18:39:34      阅读:149      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!