Question
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If such an arrangement is not possible, it must rearrange it as the lowest possible order (i.e., sorted in ascending order).
The replacement must be in place and use only constant extra memory.
https://leetcode.com/problems/next-permutation/
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
| class Solution { public void nextPermutation(int[] nums) { if (nums == null || nums.length == 0) return; int replace = nums.length - 2; while (replace >= 0) { if (nums[replace] < nums[replace + 1]) break; replace--; } if (replace < 0) { Arrays.sort(nums); return; } int lgrIdx = replace + 1; while (lgrIdx < nums.length && nums[lgrIdx] > nums[replace]) { lgrIdx++; } int tmp = nums[replace]; nums[replace] = nums[lgrIdx - 1]; nums[lgrIdx - 1] = tmp; Arrays.sort(nums, replace + 1, nums.length); } }
|
Complexity:
Time complexity: O(nlogn)
Space complexity: O(1)