LeetCode刷题day031 (Jieky)

该博客详细解析了LeetCode第31题的解决方案,即如何在原地实现数组的下一个更大排列。博主首先介绍了问题背景和要求,然后通过代码解释了解题思路:从数组末尾开始找到第一个不升序的元素,然后在其左侧找到大于它的最小值进行交换,最后将交换位置前的子数组反转,从而得到下一个排列。这种方法确保了结果是升序排列中最小的。
摘要由CSDN通过智能技术生成

LeetCode第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 and use only constant 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 NextPermutation{
	public static void main(String[] args){
		int[] nums = {3,2,1};
		NextPermutation np = new NextPermutation();
		np.nextPermutation(nums);
		for(Integer temp : nums){
            System.out.println(temp);
        }
	}
	
	/*
	将数组中的数重新排序,获得一个比当前数大的排序后最小数
	若这样的数不存在,则将数值中的数,按升序排序
	
	要使尽可能第的位变大,这样就可以使得获得的数尽可能小,所以从最低位开始进行放大操作
	放大操作是基于交换操作
		若是与交换位的左边进行交换不一定获得符合要求的数:158 4 76531 -> 458 1 76531、148 5 76531
		若是与交换位的右边进行交换获得符合要求的数:158 4 76531 -> 158 5 76431(刚好)、158 6 74531(太大)、158 3 76541(变小)
			158 5 76431(刚好) -> 158 5 13567
	总结:从十位寻找合适的交换位(即不再升序的位),在交换位之前寻找比他大的最小数,将这两个数进行交换,将交换位之前的数逆序
	*/ 
	
	public void nextPermutation(int[] nums) {
		int i = nums.length - 2;
		//找到第一个不再递增的位置
		while (i >= 0 && nums[i + 1] <= nums[i]) {
			i--;
		}
		//如果到了最左边,就直接倒置输出
		if (i < 0) {
			reverse(nums, 0);
			return;
		}
		//找到刚好大于 nums[i]的位置
		int j = nums.length - 1;
		while (j >= 0 && nums[j] <= nums[i]) {
			j--;
		}
		//交换
		swap(nums, i, j);
		//利用倒置进行排序
		reverse(nums, i + 1);

	}

	private void swap(int[] nums, int i, int j) {
		int temp = nums[j];
		nums[j] = nums[i];
		nums[i] = temp;
	}

	private void reverse(int[] nums, int start) {
		int i = start, j = nums.length - 1;
		while (i < j) {
			swap(nums, i, j);
			i++;
			j--;
		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值