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
Solution:interative
思路:
Screen Shot 2017-11-21 at 12.24.23.png
Time Complexity: O(N) Space Complexity: O(1)
Solution Code:
class Solution {
public void nextPermutation(int[] nums) {
if(nums == null || nums.length < 2) return;
// find first "/" from end to start
int index = -1;
for(int i = nums.length - 1; i >= 1; i--) {
if(nums[i - 1] < nums[i]) {
index = i;
break;
}
}
if(index == -1) {
reverse(nums, 0, nums.length - 1);
}
else {
index -= 1; // step back
// find its nearest larger element in sorted array
int next_pos = 0;
for(int i = nums.length - 1; i > index; i--) {
if(nums[i] > nums[index]) {
next_pos = i;
break;
}
}
swap(nums, index, next_pos);
reverse(nums, index + 1, nums.length - 1);
}
}
private void swap(int[] nums, int i, int j){
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
private void reverse(int[] nums, int start, int end) {
while(start < end) {
swap(nums, start, end);
start++;
end--;
}
}
}