题目来源: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;
}
}