首页 > 解决方案 > 使用 HashSet 从排序数组中删除重复项

问题描述

我对此有一个问题:

对象显示给定一个排序数组,删除重复的地方,使每个元素只出现一次并返回新的长度。不要为另一个数组分配额外的空间,您必须使用常量内存来执行此操作。例如,给定输入数组 nums = [1,1,2],您的函数应返回长度 = 2,其中包含 nums 的前两个元素分别为 1 和 2。在新长度之外留下什么并不重要。

我使用 HashSet 来做这个问题,但结果总是显示 [1,1]。我不知道有人可以帮我知道问题出在哪里吗?

我的代码:

class Solution {
    public int removeDuplicates(int[] nums) {
        if (nums.length == 0) return 0;
        Set<Integer> numset = new HashSet<>();
        for(int i:nums){
            numset.add(i);
        }
        return numset.size();
    }
}

你的输入 [1,1,2] 你的答案 [1,1] 预期的答案 [1,2]

标签: javahashset

解决方案


假设您有一个排序数组:

int[] nums = { 1, 2, 2, 2, 4, 5, 5, 5, 7, 7, 8 };

... walk through nums, at some read position check for being a duplicate,
... (otherwise) write it compact at the write position
... return new length

覆盖数字。

由于我不想破坏对编码的任何满足感,请继续...

策略:在纸上解决问题。


推荐阅读