java - 使用 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]
解决方案
假设您有一个排序数组:
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
覆盖数字。
由于我不想破坏对编码的任何满足感,请继续...
策略:在纸上解决问题。
推荐阅读
- html - 如何在点击时重置我在 Angular 中创建的计时器?
- bash - sed 替换:替换字符串是需要扩展的变量并且包含斜杠
- excel - Excel VBA:在开关情况下使用字符+整数
- amazon-web-services - 有没有办法在 AppStream 2.0 中触发主机用户浏览器上的操作?
- javascript - Draggable JS 中的固定元素
- javascript - 在 javascript 槽代码中的数组中添加对象?
- php - 将变量传递给 Curl Post 字段
- c# - 从排序数组逻辑中删除重复项在 C# 中为正确答案抛出异常
- javascript - 基于 withGraphFetched 结果从 Objection/Knex 查询中排除结果
- r - 使用 R 在多个轴上具有多个刻度的雷达图(蜘蛛图)