2019年1月21日星期一

[LeetCode] 31. Next Permutation

这道题卡了好久,终于做出来了,都要绕晕了ㄟ(▔▽▔)ㄏ
class Solution {
public void nextPermutation(int[] nums) {
// Find longest non-increasing suffix
int i = nums.length - 1;
while (i > 0 && nums[i] <= nums[i - 1]) {
i--;
}
int pivot = i - 1;
if (pivot != -1) {
// Find rightmost successor to pivot in the suffix
int rightmostSuccessor = nums.length - 1;
while (nums[rightmostSuccessor] <= nums[pivot]) {
rightmostSuccessor--;
}
// Swap with pivot
int tmp = nums[pivot];
nums[pivot] = nums[rightmostSuccessor];
nums[rightmostSuccessor] = tmp;
}
// Reverse the suffix
int start = pivot + 1;
int end = nums.length - 1;
while (start < end) {
int tmp = nums[start];
nums[start] = nums[end];
nums[end] = tmp;
start++;
end--;
}
}
}
比较无聊的一点是,如果没有看到这个算法,是不太可能做出来的 Next lexicographical permutation algorithm

没有评论:

发表评论