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, 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
题目大意:实现一个排列,找出下一个最大的排列,如果没有下一个最大排列,则输出最小排列。
思路:首先从后向前遍历数组,找到数组的第一个下降位置,退出遍历,未找到下降位置,即数组为降序排列,则直接反转数组,否则,从后向下降位置找到第一个大于下降位置的值,并将其与下降位置处的值进行交换,之后对下降位置后的部分进行反转。
代码:
class Solution { public void nextPermutation(int[] nums) { int n = nums.length; if (n < 2) { return; } int index = n - 1; while (index > 0) { if (nums[index - 1] < nums[index]) { break; } index--; } if (index == 0) { reverseSort(nums, 0, n - 1); } else { int val = nums[index - 1]; int j = n - 1; while (j >= index) { if (nums[j] > val) { break; } j--; } swap(nums, index - 1, j); reverseSort(nums, index, n - 1); } } private void swap(int[] nums, int i, int j) { int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } private void reverseSort(int[] nums, int start, int end) { if (start > end) { return; } for(int i=start;i<=(start+end)/2;i++) { swap(nums, i, start + end - i); } } }