leetcode-31 Next Permutation 数字排列组合找到下一个更大值

本文介绍如何通过算法实现数组中数字的下一个字典序排列,并详细解释了实现步骤与关键代码。文章通过实例说明了如何找到并交换指定位置的数值,以及如何进行数组的反转操作。

问题描述:

Implementnext permutation, which rearranges numbers into the lexicographically nextgreater permutation of numbers.

Ifsuch arrangement is not possible, it must rearrange it as the lowest possibleorder (ie, sorted in ascending order).

Thereplacement must be in-place, do not allocate extra memory.

Hereare some examples. Inputs are in the left-hand column and its correspondingoutputs are in the right-hand column.
1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1

 

问题分析:

列举一个例子:1,1,5,7,6,4,3,1其下一个数是1, 1,6,1,3,4,5,7

可以看到5和6调换了顺序,然后6之后的数组{7,5,4,3,1}然后再逆序即可得到结果;

之所调换5和6,是从后往前遍历数组,直至发现第一个nums[i] < nums[i + 1]的位置i;然后交换nums[i]与i之后数组中的最小值nums[j];

再反转i+1到末位的数组即可。

 

代码:

public class Solution {
   public void nextPermutation(int[] nums) {
    if (nums.length <= 1)
        return;
 
    // 找到第一个nums[i] < nums[i +1]的位置i;注意从后往前寻找
    int i = nums.length - 2;
    while ((i >= 0) && (nums[i] >=nums[i + 1]))
        i--;
    // 如果上述情况存在,则表示有下一个更大值
    if (i >= 0) {
        // 找到i位置后大于nums[i]的最小值nums[j],然后交换nums[i]与nums[j]
        // 根据前面遍历性质知后面i后的数组肯定是降序排列的,故找最小值仅需要从末位开始比较就可
        int j = nums.length - 1;
        while (nums[i] >= nums[j])
            j--;
        exchange(nums, i, j);
    }
 
    // 再反转i到末尾所有元素值,这里采用双指针法反转
    for (int start = i + 1, end = nums.length - 1; start < end; start++, end-- )
        exchange(nums, start,end);       
   }
 
   // 交换数组内两个位置数据
   private void exchange(int[] nums, int i, int j) {
    int temp = nums[i];
    nums[i]  = nums[j];
    nums[j]  = temp;
   }
}

相关问题:

leetcode-46、47 Permutations/II 数字的排列组合

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值