Leetcode-31. Next Permutation

前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN,mcf171专栏。

博客链接:mcf171的博客

——————————————————————————————

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.

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

这个题目说实话,一开始没看懂什么叫做下一个排列,然后在网上看了一下其他人的解释才明白。感觉这个题目本身和算法没太多关系,主要还是找规律。规律就是从后往前找。找到第一个递增的位置,然后再往后找,找到后面这些数中比递增位置数大,但又是这些数中最小的。

比如输入是6 5 4 8 7 5 1

首先肯定从后面开始看,1和5调换了没有用。7、5和1调换了也没有效果,因此而发现了8、7、5、1是递减的。如果想要找到下一个排列,找到递增的位置是关键。因为在这里才可以使其增长得更大。于是找到了4,显而易见4过了是5而不是8或者7更不是1。因此就需要找出比4大但在这些大数里面最小的值,并将其两者调换。那么整个排列就成了:6 5 5 8 7 4 1然而最后一步将后面的8 7 4 1做一个递增。

代码如下:Your runtime beats 45.41% of java submissions.

public class Solution {
    public void nextPermutation(int[] nums) {
        
	if(nums == null) return;
	if(nums.length <= 1) return;
	
	int j = nums.length - 1;
	int smallest = nums.length - 1;
	while(j > 0){
		if(nums[j] > nums [j - 1]){j--; break;}
		 j--;
	}
	if(j == 0  && nums[j] >= nums[j+1]){
		Arrays.sort(nums);
		return;
	}
	smallest = j + 1;
	for(int i = j ; i < nums.length; i++){
		if(nums[i] < nums[smallest] && nums[i] > nums[j]) smallest = i;
	}
	int temp = nums[smallest];
	nums[smallest] = nums[j];
	nums[j] = temp;
	
	for(int i = j + 1; i < nums.length; i ++){
		smallest = i;
		for(j = i; j < nums.length; j ++){
			if(nums[j] < nums[smallest]) smallest = j;
		}
		temp = nums[smallest];
		nums[smallest] = nums[i];
		nums[i] = temp;
	}
	return;
	
	
    }
}





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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值