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

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;
        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值