LeetCode T31 Next Permutation

题目地址:

中文:https://leetcode-cn.com/problems/next-permutation/
英文:https://leetcode.com/problems/next-permutation/

题目描述:

Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.

If such an arrangement is not possible, it must rearrange it as the lowest possible order (i.e., sorted in ascending order).

The replacement must be in place and use only constant extra memory.

Example 1:

Input: nums = [1,2,3]
Output: [1,3,2]

Example 2:

Input: nums = [3,2,1]
Output: [1,2,3]

Example 3:

Input: nums = [1,1,5]
Output: [1,5,1]

Example 4:

Input: nums = [1]
Output: [1]

Constraints:

1 <= nums.length <= 100
0 <= nums[i] <= 100

思路:

先想一下字典序什么样,比如123和321,最小的排列是单个数字从小到大,最大的排列是单个数字从大到小。所以如果判断最小,那就要看从左到右是不是非递减的;最大的话就是从右到左看是不是非递减的。
从右到左找到这样一个数对:右边的nums[i]大于左边的nums[i-1],然后重排包括这一对数在内右边的数字,找到一个比nums[i-1]大的就可以,剩下的数字按从小到大向右排列就可了。

题解:

class Solution {
    public void nextPermutation(int[] nums) {
        boolean flag_mid = false;
        int m=0,n=0;
        int last_ = nums.length-1;
        while (last_>0){
            for(int i=last_;i>0;--i){
                if(nums[i-1]<nums[i]){
                    m = i-1;
                    n = i;
                    flag_mid = true;
                    break;
                }
            }
            if(flag_mid) break;
            --last_;
        }//如果找到前面小于后面的情况
        if(flag_mid){
            //然后从i-1位开始重排列
            int temp = nums[m];
            int t=0;
            Arrays.sort(nums,m,nums.length);
            for(int i=m;i<nums.length;++i)
                if(nums[i]>temp) {
                    t = i;
                    break;
                }
            temp = nums[m];
            nums[m] = nums[t];
            nums[t] = temp;
            Arrays.sort(nums,m+1,nums.length);
        }else
            for(int i=0;i<nums.length/2;++i) {
                int temp = nums[i];
                nums[i] = nums[nums.length-i-1];
                nums[nums.length-i-1] = temp;
            }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值