解法一
双指针
使用双指针left、right,找到第一个nums[left] !== nums[right]的元素,将nums[right]填到nums[left]上,然后left++、right++。
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
|
var removeDuplicates = function (nums) { let left = (right = 0); while (right < nums.length) { while (nums[right] === nums[left]) { right++; } if (right < nums.length && nums[left] !== nums[right]) { if (right > left + 1) { nums[left + 1] = nums[right]; } left++; } right++; } return left + 1; };
|
解法二
三次翻转
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
var rotate = function (nums, k) { const length = nums.length; const count = k % length; if (count === 0) return; function reverse(left, right) { while (left < right) { [nums[left], nums[right]] = [nums[right], nums[left]]; left++; right--; } } reverse(0, length - 1); reverse(0, count - 1); reverse(count, length - 1); };
|