algorighm/top-interview-leetcode150/numbers-and-strings/80删除有序数组中重复项2.js

47 lines
1.3 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 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);