This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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--; | |
} | |
} | |
} |
没有评论:
发表评论