题目:
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
点击解题:Next Permutation
分析:寻找给定数列的下一个排列,如果不存在,则找出该数列的初始排列。
思路:
下一个数列一定是当前数列最小增加值,即题目转化为找出当前数列最小增量。即为下一个数列,如示意图示:
1.从右到左找出当前数列的最长降序排列,这此时数列分成两部分,记为左右两部分,以1,2,5,4,3,0为例,该数列是以(1,2)开头最大数列,则下一个数列要比(1,2)大,且最小增量,由数列可知,即要以(1,3)开头,而3为最长降序排列中第一个大于“2”的数字,如果是以(1,4)开头无法得到正确的下一个排序,将交换后得到数列从“5”到“0”倒置,即可。上述文字等价于:
(1).对于给定数组nums,从右到左找出nums[k] < nums[k - 1], k = nums.length - 2 开始递减迭代, 满足要求的k : i = k;
(2).从右到左找出第一个大于nums[i]的数字nums[k],k = nums.length - 1 开始递减迭代,满足要求的k : j = k;
(3).将nums[i] 与nums[j]交换,即下一个排列以(1,3)开头
(4).将i+ 1 到 nums.length - 1的排列倒置
Java代码: Accepted
public class Solution {
public void nextPermutation(int[] nums) {
//Save the first index of nums[i] < nums[k] from right to left
int i = 0;
//Save the first index of nums[j] > nums[i] from right to left
int j = 0;
//To find the first index of nums[i] < nums[k] from right to left
for(int k = nums.length - 2;k > 0;k --){
if(nums[k] < nums[k + 1]){
i = k;
break;
}
}
//To find the first index of nums[j] > nums[i] from right to left
for(int l = nums.length - 1;l > 0;l --){
if(nums[l] > nums[i]){
j = l;
break;
}
}
//Swap nums[i] and nums[j]
int swap = nums[i];
nums[i] = nums[j];
nums[j] = swap;
//Reverse the sub array from i + 1 (or 0) to nums.length - 1
int n = 0;
if(i == 0 && j == 0){
n = 0;
}else{
n = i + 1;
}
int m = nums.length - 1;
while(n < m){
int temp = nums[n];
nums[n] = nums[m];
nums[m] = temp;
m --;
n ++;
}
}
}
Python 代码:Accepted
class Solution(object):
def nextPermutation(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
"""
i for the first index nums[k] > nums[k + 1] from right to left
j for the first index nums[i] < nums[j] from right to left
"""
i = j = 0
#To find the the first index nums[k] > nums[k + 1] from right to left
k = len(nums) - 2
while(k > 0):
if(nums[k] < nums[k + 1]):
i = k
break
k -= 1
#To find the the first index nums[i] < nums[j] from right to left
k = len(nums) - 1
while(k > 0):
if(nums[k] > nums[i]):
j = k
break;
k -= 1
#Swap nums[i] and nums[j]
nums[i],nums[j] = nums[j],nums[i]
#Reverse elements for i + 1(or 0) to len(nums) - 1
if(i == 0 and j == 0):
n = 0
else:
n = i + 1
m = len(nums) - 1
while(n <= m):
nums[n],nums[m] = nums[m],nums[n]
n += 1
m -= 1
参考文献:
Permutation wiki:http://www.wikiwand.com/en/Permutation#/Cycle_notation
Next lexicographical permutation algorithm:http://www.nayuki.io/page/next-lexicographical-permutation-algorithm