LeetCode Next Permutation

Description:

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.

Solution:

这里我们可以假设有这么几个数字:d c b a

先忽略相等的情况,那么可以发现

if a > b 

then switch a, b

else // (a<b) 

if b > c

then b,a,c (a<c) or b,c,a (c<a)

else // a<b<c

then ...

综上就是这么几个结论:

找到从后往前第一个增长的点,假设增长的点位ascendingPoint,简称ap。(这里因为代码方便,我设置的是ap-1,ap是增长两个前后点)。

那么需要把所有[ap,length()-1]的点中找到比ap-1点的数值大的 最小值(大于ap-1的最小点),这个最小点就是变换之后在ap-1这个位置的数值,后面的排序即可。

如果ap=0,就表示所有的点递减,那么按照题目要求重新排序就好。

import java.util.Arrays;

public class Solution {
	public void nextPermutation(int[] nums) {
		int ascendingPoint = getAscendingPoint(nums);
		if (ascendingPoint == 0) {
			Arrays.sort(nums);
		} else {
			int minBigger = Integer.MAX_VALUE;
			for (int i = nums.length - 1; i >= ascendingPoint; i--) {
				if (nums[i] > nums[ascendingPoint - 1] && nums[i] < minBigger) {
					minBigger = nums[i];
					nums[i] = nums[ascendingPoint - 1];
					nums[ascendingPoint - 1] = minBigger;
				}
			}
			Arrays.sort(nums, ascendingPoint, nums.length);
		}
	}

	int getAscendingPoint(int nums[]) {
		for (int i = nums.length - 1; i > 0; i--)
			if (nums[i] > nums[i - 1])
				return i;
		return 0;
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值