#31. Next Permutation
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
这个题需要找规律,可以发现,如果全降序,证明此时是全排列的最后一种情况,下一种是升序。对于其他的情况,从后往前看,找到第一个不符合升序的,找到它后面的第一个比它大的,置换,剩下的从前往后升序排列。
var nextPermutation = function(nums) {
let i = nums.length-2;
while(nums[i]>=nums[i+1]) {
i--;
}
if(i>=0) {
let j = nums.length-1;
while(nums[j]<=nums[i]) {
j--;
}
swap(i,j);
}
reverse(nums,i+1);
function swap(i,j) {
let temp = nums[i];
nums[i]=nums[j];
nums[j]=temp;
}
function reverse(nums,i) {
let j=nums.length-1;
while(j>=i) {
swap(i,j);
i++;
j--;
}
}
return nums;
};
onefanyf
发布了63 篇原创文章 · 获赞 0 · 访问量 268
私信
关注