LeetCode 31. Next Permutation

题目来源:https://leetcode.com/problems/next-permutation/

问题描述

31. Next Permutation

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 and use only constant 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

------------------------------------------------------------

题意

给出一个数组,返回十进制意义下比该排列对应的数更大的数中最小者对应的排列,若当前排列在十进制意义下已经是最大,则返回最小排列。要求原地操作,只能开辟O(1)的内存空间。

------------------------------------------------------------

思路

从数组尾端开始向前遍历,直到找到一个位置valley,valley位置的值比valley+1位置的值小(同时这样还可以保证valley+1位置到数组尾端的序列<记作尾端序列>是降序的)。

再次从尾端向前遍历,直到找到一个位置i,使得i位置的值大于valley位置的值(由于尾端序列降序性,保证了i位置的值是尾端序列中比valley位置的值大的最小者)。交换valley的值和i的值,并翻转尾端序列,使之成为升序序列。

如果原数组是完全降序的,则找不到valley位置,此时直接翻转原数组即可。

一个例子:

 

 

 

valley

 

 

 

 

 

Step 1

1

9

3

9

8

4

3

1

 

 

 

valley

 

 

i

 

 

Step 2

1

9

3

9

8

4

3

1

 

 

 

valley

 

 

i

 

 

Step 3

1

9

4

9

8

3

3

1

Step 4

1

9

4

1

3

3

8

9

------------------------------------------------------------

代码

class Solution {
    public void nextPermutation(int[] nums) {
        int i = 0, n = nums.length, valley = -1, tmp = 0;
        if (n == 0 || n == 1)
        {
            return;
        }
        for (i=n-2; i>=0; i--)
        {
            if (nums[i] < nums[i+1])
            {
                valley = i;
                break;
            }
        }
        if (valley == -1)
        {
            for (i=0; i<n/2; i++)
            {
                tmp = nums[i];
                nums[i] = nums[n-1-i];
                nums[n-1-i] = tmp;
            }
        }
        else
        {
            for (i=n-1; i>valley; i--)
            {
                if (nums[i] > nums[valley])
                {
                    tmp = nums[valley];
                    nums[valley] = nums[i];
                    nums[i] = tmp;
                    break;
                }
            }
            int end = valley+1+(n-valley-1)/2;
            for (i=valley+1; i<end; i++)
            {
                tmp = nums[i];
                nums[i] = nums[n-i+valley];
                nums[n-i+valley] = tmp;
            }
        }
        return;
    }
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值