LeetCode刷题笔录Next Permutation

本文介绍了一个算法问题——寻找数组中字典序的下一个更大排列。文章详细解释了算法思路,并提供了一个Java实现示例,包括如何查找违反递增顺序的元素并进行相应的交换和反转操作。

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

这题能算算法题么?像是智力题。

从数组尾部开始向前数,如果一直都是increasing order的话,那么就没有更大的permutation。如果遇到了一个违反increasing order的数,那么就有更大的permutation。找到了这个数的index后,再从尾部开始向前找,找到第一个比violator更大的数(swap index)的index,然后交换这两个数。

比如3 6 4 2 1这个数组,violator就是3,swap index就是4.交换以后变成4 6 3 2 1。最后再把violator index右边的所有数字反序,即本来是升序排列的变成降序排列。最后结果就是4 1 2 3 6.

public class Solution {
    public void nextPermutation(int[] num) {
        if(num.length < 2)
            return;
        //find the index of the first number that violates increasing order
        int notIncreasingIndex = num.length - 2;
        while(notIncreasingIndex >= 0){
            if(num[notIncreasingIndex] < num[notIncreasingIndex + 1]){
                break;
            }
            notIncreasingIndex--;
        }
        
        //find the first index that is bigger than the not-increasing index
        if(notIncreasingIndex >= 0){
            int swapIndex = num.length - 1;
            while(num[swapIndex] <= num[notIncreasingIndex] && swapIndex > notIncreasingIndex){
                swapIndex--;
            }
            swap(num, swapIndex, notIncreasingIndex);
        }
        
        //reverse all elements to the right of the not-increasing index
        notIncreasingIndex++;
        int end = num.length - 1;
        while(end > notIncreasingIndex){
            swap(num, end, notIncreasingIndex);
            end--;
            notIncreasingIndex++;
        }

    }
    
    public void swap(int[] num, int i, int j){
        int temp = num[i];
        num[i] = num[j];
        num[j] = temp;
    }
}


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值