java - 通过 Haspmap 求解单个数字,返回始终为“@”
问题描述
这是 leetcode 的一个问题。Leetcode - 单数 I .
- 单数: 给定一个非空整数数组,除一个外,每个元素都出现两次。找到那个单一的。 输入:[2,2,1] 输出:1
我想使用hashmap来解决它,但是我的返回键总是“@”是错误的。
这是代码:
class Solution {
public int singleNumber(int[] nums) {
char[] y = ("" + nums).toCharArray();
int size=y.length;
Map<Character,Integer>map=new HashMap<>();
int i =0;
while(i!=size) {
if(map.containsKey(y[i])==false) {
map.put(y[i],1);
}
else {
int oldval=map.get(y[i]);
int newval=oldval+1;
map.put(y[i],newval);
}
++i;
}
Set<Map.Entry<Character,Integer>>hmp=map.entrySet();
for(Map.Entry<Character,Integer>data:hmp) {
if(data.getValue()==1){
return data.getKey();
}
}
return 0;
}
}
我不知道出了什么问题。(也许是 getkey() 部分?)
我出现了你的所有帮助!
解决方案
使用按位异或:
int result = 0;
for (int n : nums) {
result ^= n;
}
return result;
这有效,因为:
a ^ 0 = a
,a ^ a = 0
a ^ b = b ^ a
(a ^ b) ^ c = a ^ (b ^ c)
所以成对的数字相互抵消,无论它们出现在数组中的什么地方。
请注意,虽然这是一种非常不同的回答方法,但您可以应用类似的方法来使用 a Map
:
Map<Integer, Integer> map = new HashMap<>();
for (int n : nums) {
if (!map.remove(n)) {
map.add(n, n);
}
}
这会在地图中添加和删除成对的项目;最后,地图中应该只剩下 1 个未配对的值。
return map.keySet().iterator().next();
(这里实际上没有理由使用 a Map
,您不妨使用 a Set
)。
推荐阅读
- html - 如何使用 CSS 属性位置添加我的图标:绝对,以便它始终保留在我添加它的密码字段中
- sql - 如何在 Oracle 插入命令中使用双表中的子查询?
- wordpress - 如何在 wordpress 的新小部件中显示简码?
- python - 如何修改熊猫数据框的日期时间对象列中的分钟数?
- python - python pandas查询列表中的值
- powershell - 将数据格式化为 API
- android - 如何在 android 的 Portraint 模式活动中以横向模式查看视图?
- for-loop - dict 为空时 Jinja2 返回错误 - 尽管前面有条件
- javascript - 谷歌单元测试看起来像自定义语法
- c++ - 将结构类型附加到另一个的最佳实践