Leetcode-31. Next Permutation

来源:互联网 发布:char占几个字节 java 编辑:程序博客网 时间:2024/06/14 14:17

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