Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

26、删除排序数组中的重复项 #48

Open
hubvue opened this issue Dec 29, 2019 · 0 comments
Open

26、删除排序数组中的重复项 #48

hubvue opened this issue Dec 29, 2019 · 0 comments

Comments

@hubvue
Copy link
Owner

hubvue commented Dec 29, 2019

题目

给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。

不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。

示例 1:

给定数组 nums = [1,1,2], 

函数应该返回新的长度 2, 并且原数组 nums 的前两个元素被修改为 1, 2。 

你不需要考虑数组中超出新长度后面的元素。

示例 2:

给定 nums = [0,0,1,1,1,2,2,3,3,4],

函数应该返回新的长度 5, 并且原数组 nums 的前五个元素被修改为 0, 1, 2, 3, 4。

你不需要考虑数组中超出新长度后面的元素。

题解

解题思路

采用一个set来标记数组中元素,如果在set中已经出现,使用数组的splice方法删除掉。

代码

/**
 * @param {number[]} nums
 * @return {number}
 */
var removeDuplicates = function(nums) {
    let set = new Set();
    for(let i = 0; i < nums.length; i ++) {
        if(set.has(nums[i])) {
            nums.splice(i, 1);
            i--;
        } else {
            set.add(nums[i]);
        }
    }
    return nums.length;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant