In last week’s boiling point activity – daily algorithm problem, there is a question like this: The next permutation, the requirement is: to implement the function to get the next permutation, the algorithm needs to rearrange the given sequence of numbers into the next larger permutation in the lexicographical order. If no next larger arrangement exists, the numbers are rearranged into the smallest arrangement (that is, in ascending order). Must be modified in place, allowing only extra constant space.
(1, 2, 3, 4) (1, 2, 3, 4) (1, 3, 4)
1 2 3 4 1 2 4 1 3 2 4 1 3 2 4 1 3 3 4 2Copy the code
You can see that the latter column is always greater than the previous column: 1234 < 1243 < 1324 < 1342 <… < 4321
Nums [length] = nums[length] = nums[length – 1] = nums[length – 1] = nums[length – 1] = nums[length – 1] = nums[length – 1] = nums[length – 1] = nums[length – 1] No problem, it’s over
If nums[length] is not the last digit, then the value of nums[length] and nums[flag1 + 1] should be determined. If nums[length] is not the last digit, then the value of nums[length] should be determined. In this case, exchange nums[flag1-1] and nums[flag1 + 1].
In the code
function nextLargerSpread(nums) { if (nums.lenght === 1) return nums; let before, after, next; let flag1 = nums.length - 1, flag2; for (let i = 0; i < nums.length; i++) { if (nums[flag1] > nums[flag1 -1 ]) { before = nums[flag1 - 1]; after = nums[flag1]; if (nums[flag1 - 1] < nums[flag1 + 1] && nums[flag1 + 1]) { flag2 = flag1 + 1; next = nums[flag1 + 1]; nums[flag1 - 1] = next; nums[flag1 + 1] = before; } else { nums[flag1 - 1] = after; nums[flag1] = before } break; } flag1--; if (flag1 === 0) { nums = nums.reverse(); } } if (flag2 < nums.length - 1 && nums[flag2 + 1]) { let start = (nums.slice(0, flag2 - 1)); let endList = nums.slice(flag2 - 1).sort(); nums = [...start, ...endList]; }};Copy the code
Last image from the Imageslr bigshot:
If you don’t understand my thinking, you can click the following link to see the picture of the answer of the boss. I was confused when I first saw this topic, and then I understood it from the picture of the boss.
Photo credit: leetcode-cn.com/problems/ne…