|
| 1 | +/** |
| 2 | + * https://leetcode.com/problems/next-permutation/description/ |
| 3 | + * Difficulty:Medium |
| 4 | + * |
| 5 | + * Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. |
| 6 | + * If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order). |
| 7 | + * The replacement must be in-place, do not allocate extra memory. |
| 8 | + * Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column. |
| 9 | + * 1,2,3 → 1,3,2 |
| 10 | + * 3,2,1 → 1,2,3 |
| 11 | + * 1,1,5 → 1,5,1 |
| 12 | + */ |
| 13 | +/** |
| 14 | + * @param {number[]} nums |
| 15 | + * @return {void} Do not return anything, modify nums in-place instead. |
| 16 | + */ |
| 17 | +var nextPermutation = function (nums) { |
| 18 | + |
| 19 | + if (nums.length < 2) return; |
| 20 | + var peak = nums.length - 1; |
| 21 | + for (var i = peak - 1; nums[i] >= nums[peak]; peak = i--); |
| 22 | + |
| 23 | + if (peak !== 0) { |
| 24 | + var swapIndex = findSwap(nums, peak, nums.length - 1, peak - 1); |
| 25 | + if (swapIndex !== -1) { |
| 26 | + swap(nums, peak - 1, swapIndex); |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + reverse(nums, peak, nums.length - 1); |
| 31 | + |
| 32 | +}; |
| 33 | + |
| 34 | +function findSwap(nums, s, e, target) { |
| 35 | + for (var i = e; i >= s; i--) { |
| 36 | + if (nums[i] > nums[target]) return i; |
| 37 | + } |
| 38 | + return -1; |
| 39 | +} |
| 40 | + |
| 41 | +function swap(nums, s, e) { |
| 42 | + var t = nums[s]; |
| 43 | + nums[s] = nums[e]; |
| 44 | + nums[e] = t; |
| 45 | +} |
| 46 | +function reverse(nums, s, e) { |
| 47 | + // var len = e - s; |
| 48 | + for (var i = 0; i < Math.ceil((e - s ) / 2); i++) { |
| 49 | + |
| 50 | + swap(nums, s + i, e - i); |
| 51 | + } |
| 52 | + // return nums; |
| 53 | +} |
| 54 | + |
| 55 | +// console.log(reverse([1, 2, 3, 4, 5], 0, 4)); |
| 56 | +// console.log(reverse([1, 2, 3, 4, 5], 3, 4)); |
| 57 | +// console.log(reverse([1, 2, 3, 4, 5], 2, 3)); |
| 58 | +// console.log(reverse([1, 2, 3, 4, 5], 1, 1)); |
| 59 | +// console.log(reverse([1, 2, 3, 4, 5], 1, 4)); |
| 60 | + |
| 61 | +// var nums = [1, 2, 5, 4, 3]; |
| 62 | +// console.log(nums); |
| 63 | +// nextPermutation(nums); |
| 64 | +// console.log(nums); |
| 65 | +// |
| 66 | +console.log('===='); |
| 67 | + |
| 68 | +var nums = [2, 3, 1]; |
| 69 | +console.log(nums); |
| 70 | +nextPermutation(nums); |
| 71 | +console.log(nums); |
| 72 | + |
| 73 | +console.log('===='); |
| 74 | + |
| 75 | +var nums = [1, 1]; |
| 76 | +console.log(nums); |
| 77 | +nextPermutation(nums); |
| 78 | +console.log(nums); |
| 79 | + |
| 80 | +console.log('===='); |
| 81 | + |
| 82 | +var nums = [3, 2, 1]; |
| 83 | +console.log(nums); |
| 84 | +nextPermutation(nums); |
| 85 | +console.log(nums); |
| 86 | + |
| 87 | + |
0 commit comments