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
| class Solution { public void nextPermutation(int[] nums) { int n = nums.length, i = n - 2; while (i >= 0 && nums[i] >= nums[i + 1]) --i; if (i >= 0) { int j = n - 1; while (j >= 0 && nums[j] <= nums[i]) --j; swap(nums, i, j); } reverse(nums, i + 1); }
private void reverse(int[] nums, int left) { int right = nums.length - 1; while (left < right) { swap(nums, left++, right--); } }
private void swap(int[] nums, int i, int j) { int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } }
|