/** * https://leetcode.cn/problems/remove-duplicates-from-sorted-array-ii/?envType=study-plan-v2&envId=top-interview-150 * @param {number[]} nums * @return {number} */ const removeDuplicates = function (nums) { if (nums.length === 0) return 0; let i = 1; // 慢指针,初始化为1,表示第一项是已经有效的 let count = 1; // 计数器,用于统计当前元素出现的次数 for (let j = 1; j < nums.length; j++) { // 快指针 if (nums[j] === nums[j - 1]) { count++; // 当前元素和前一个元素相同,计数器加1 } else { count = 1; // 如果不同,重置计数器 } if (count <= 2) { nums[i] = nums[j]; // 如果当前元素不超过2次,移动到有效位置 i++; // 慢指针向前移动 } } return i; // 最终慢指针的位置即为去重后的元素个数 }; // var removeDuplicates = function(nums) { // const n = nums.length; // if (n <= 2) { // return n; // } // let slow = 2, fast = 2; // while (fast < n) { // if (nums[slow - 2] != nums[fast]) { // nums[slow] = nums[fast]; // ++slow; // } // ++fast; // } // return slow; // }; const numss = [0, 0, 1, 1, 1, 1, 2, 3, 3]; console.log(removeDuplicates(numss)); console.log(numss);