Java for LeetCode 031 Next Permutation

本文详细介绍了如何使用Java实现NextPermutation算法,用于在给定整数数组中找到下一个字典排序的排列。该算法在遍历数组时,通过交换元素的位置来找到满足条件的下一个排列,并将其原地修改,而无需额外内存。

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

 

转载于:https://www.cnblogs.com/tonyluis/p/4485612.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值