LeetCode:Next Permutation

Next Permutation




Total Accepted: 70533  Total Submissions: 261357  Difficulty: Medium

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

Subscribe to see which companies asked this question

Hide Tags
  Array























思路:

下一个排列数,定义:比当前数大的最小数。

1.从左往右找到第一个“顺”,即nums[i-1] <nums[i],因此nums[i,n-1]都是“逆序”;

2.从定义可知,我们要从[i,n-1]中找一个最小的数与nums[i-1]交往,然后将nums[i,n-1]“顺序”排序即可。

如:nums = [6,2,5,4,3,1], n = 6;

由1)找到i = 2,nums[2,5] = [5,4,3,1]是“逆序”;

由2)交换后得 nums=[6,3,5,4,2,1],再将[i, n-1]顺序,得解[6,3,1,2,4,5];

由于[i, n-1]已是逆序,直接逆序就变成“顺序”,时间O(n),即总时间O(n);


java code:

public class Solution {
    public void nextPermutation(int[] nums) {
        
        int n = nums.length;
        int i = n-1;
        // 从左到右,找到第一个“顺序”位置
        while(i > 0) {
            if(nums[i-1] < nums[i]) break;
            i--;
        }
        
        if(i==0) {
            reverse(nums, 0, n-1);
            return;
        }
        
        // 找到第一个大于i位置值的下标j,并与i位置值交换
        int j = n-1;
        int val = nums[i-1];
        while(i < j && val >= nums[j]) j--;
        swap(nums, i-1, j);
        // 逆序[i,n-1]部分
        reverse(nums, i, n-1);
        
    }
    
    // 自定义函数:逆序
    void reverse(int[] nums, int lo, int hi) {
        while(lo < hi) {
            swap(nums, lo, hi);
            lo++;hi--;
        }
    }
    // 交换
    void swap(int[] nums, int lo, int hi) {
        nums[lo] ^= nums[hi];
        nums[hi] ^= nums[lo];
        nums[lo] ^= nums[hi];
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值