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

31 lines
1.1 KiB
JavaScript
Raw Permalink 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/?envType=study-plan-v2&envId=top-interview-150
* @param {number[]} nums
* @return {number} 不重复元素的数量
*/
const removeDuplicates = function (nums) {
// 直接利用Set的去重特性hash
const numSet = new Set(nums);
let i = 0;
for (const num of numSet) {
nums[i] = num;
i++;
}
return numSet.size;
};
// 上面的方法虽然好理解但是需要遍历整个数组才能转换成Set加上hash操作并不是最优解。因为提供的nums已经是一个“非严格递增的数组”
// 只需利用双指针处理即可首先定义两个指针p1,p2,p1指向第一个元素p2指向第二个元素如果有的话p2开始遍历如果遍历到得元素和nums[p1]
// 不相等p1++ 并把这个值赋值到p1的位置最后返回p1+1
const removeDuplicates2 = function (nums) {
if (nums.length < 2) return 1;
let p1 = 0;
for (let p2 = 1; p2 < nums.length; p2++) {
if (nums[p1] !== nums[p2]) {
nums[++p1] = nums[p2];
}
}
return p1 + 1; // 下标加1表示个数
};