我对此有一个问题:
该对象表明,给定一个已排序的数组,就地删除重复项,以便每个元素仅出现一次并返回新的长度。 不要为另一个数组分配额外的空间,您必须使用常量内存来完成此操作。例如, 给定输入数组 nums = [1,1,2], 您的函数应返回 length = 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]
最佳答案
假设你有一个排序数组:
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
覆盖数字。
因为我不想破坏编码的任何满意度,所以继续......
策略:在纸上解决问题。
关于java - 使用 HashSet 从排序数组中删除重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50334265/