
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
-
所谓下一个排列,就是按正数大小进行字典序排序后的下一个排列。如123 -> 132 -> 213 -> 231…
-
1234567891011121314151617181920212223242526272829303132public void (int[] nums) {boolean flag = false;for (int i = nums.length - 2; i >= 0; i--) {for (int j = nums.length - 1; j > i ; j--) {if (nums[j] > nums[i]) {exchange(nums, i, j);flag = true;while (i + 1 <= nums.length - 1) {reverse(nums, i + 1, nums.length - 1);return;}}}}if (!flag) {reverse(nums, 0, nums.length - 1);}}public void reverse(int[] nums, int start, int end) {int len = start;for (int i = 0; i <= len / 2; i++) {exchange(nums, start++, end - i);}}public void exchange(int[] nums, int i, int j) {int temp = nums[i];nums[i] = nums[j];nums[j] = temp;}




近期评论