1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| class Solution { public void nextPermutation(int[] nums) { if (nums.length < 2) return; int n = nums.length;
int left = n - 2;
while (left >= 0) { if (nums[left] < nums[left + 1]) { int j = n - 1; while (nums[j] <= nums[left]) { j--; }
swap(nums, left, j);
reverse(nums, left + 1, n - 1); return; } left--; }
reverse(nums, 0, n - 1); }
private void swap(int[] nums, int i, int j) { int tmp = nums[i]; nums[i] = nums[j]; nums[j] = tmp; }
private void reverse(int[] nums, int start, int end) { while (start < end) { swap(nums, start++, end--); } } }
|