leetCode 31.Next Permutation (下一个字典序排序) 解题思路和方法

来源:互联网 发布:java中文版 编辑:程序博客网 时间:2024/05/18 11:25
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, 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


思路:此题是我目前做过的leetCode中感觉最难的题,它的难在于算法很难自己短时间实现,如果以前没有做过这样的题,几乎很难很快的有思路解出来。在参考网上资料之前,我也尝试了好几种解法,但是没有一种能达到效果。最后参考资料,才恍然:这尼玛也可以这样做,但是臣妾很难想到啊!

题目的整体思路是,从后往前读,当后面的数比前面的数大时,在开一个循环,从后开始于当前数比较,当比当前数大时,交换。然后再从当前数的后一位开始,直到最后反序即可。

具体代码和注释如下:

public class Solution {    public void nextPermutation(int[] nums) {        if(nums.length <= 1){            return;        }        for(int i = nums.length - 1;i > 0; i--){            if(nums[i] > nums[i-1]){//如果nums[i] > nums[i-1]                //再从后往前判断有否数字比nums[i-1]大            int j = nums.length - 1;                for(; j >= i -1;j--){                if(nums[j] > nums[i-1]){                break;//如有,则结束循环,保留j的值                }                }                //将nums[j]和nums[i-1]交换                int temp = nums[j];                nums[j] = nums[i-1];                nums[i-1] = temp;                                //从i开始反序(即交换位置的地方开始反序)                for(j = 0; j < (nums.length - (i))/2;j++){                int k = nums.length - 1 - j;                int m = nums[j+i];                nums[j+i] = nums[k];                nums[k] = m;                }                return;            }        }         //如果到最后没有交换的数据,则说明是降序排列,需要升序排列        for(int i = 0; i < nums.length/2;i++){            int j = nums.length - 1 - i;//双指针排序,交换首尾对应的两两数据即可            int temp = nums[i];            nums[i] = nums[j];            nums[j] = temp;        }    }}


0 0
原创粉丝点击