使用 Hashmap 查找单个整数
Find single integer using Hashmap
一道编码题:Given an array of integers, every element appears twice except for one. Find that single one.
需要a linear runtime complexity
。
我的解决方案:
public class Solution {
public int singleNumber(int[] A) {
HashMap<Integer, Integer> lut = new HashMap<Integer, Integer>();
for (int i=0; i<A.length; i++){
if(lut.containsKey(A[i])){
lut.remove(A[i]);
}
else{
lut.put(A[i],1);
}
}
Set<Integer> keys = lut.keySet();
System.out.println(keys.size());
for(Integer integer: keys)
return integer;
return (Integer) null;
}
}
我认为复杂度是O(n)
,因为它只遍历数组一次并且HashMap
使用固定的时间来获取一个元素。但是网上判断后说我的代码time limit
。有人可以指出为什么这超过了时间限制吗?如何改进?
我怀疑时间限制是在考虑具体实施的情况下设置的。你的解决方案看起来对我来说应该是线性时间 - 但它可能是一个比这段代码大得多的常数因子:
public int findSingleNumber(int[] array) {
int result = 0;
for (int item : array) {
result ^= item;
}
return result;
}
这利用了这样一个事实,即除了我们想要的项目之外的所有项目都恰好出现两次,因此如果将它们异或在一起,它们将相互抵消。我们只剩下我们要找的号码。
我想补充一点,像这样的谜题很有趣并且可以拓展思维 - 但解决方案很少是您想要在实际应用中使用的。
一道编码题:Given an array of integers, every element appears twice except for one. Find that single one.
需要a linear runtime complexity
。
我的解决方案:
public class Solution {
public int singleNumber(int[] A) {
HashMap<Integer, Integer> lut = new HashMap<Integer, Integer>();
for (int i=0; i<A.length; i++){
if(lut.containsKey(A[i])){
lut.remove(A[i]);
}
else{
lut.put(A[i],1);
}
}
Set<Integer> keys = lut.keySet();
System.out.println(keys.size());
for(Integer integer: keys)
return integer;
return (Integer) null;
}
}
我认为复杂度是O(n)
,因为它只遍历数组一次并且HashMap
使用固定的时间来获取一个元素。但是网上判断后说我的代码time limit
。有人可以指出为什么这超过了时间限制吗?如何改进?
我怀疑时间限制是在考虑具体实施的情况下设置的。你的解决方案看起来对我来说应该是线性时间 - 但它可能是一个比这段代码大得多的常数因子:
public int findSingleNumber(int[] array) {
int result = 0;
for (int item : array) {
result ^= item;
}
return result;
}
这利用了这样一个事实,即除了我们想要的项目之外的所有项目都恰好出现两次,因此如果将它们异或在一起,它们将相互抵消。我们只剩下我们要找的号码。
我想补充一点,像这样的谜题很有趣并且可以拓展思维 - 但解决方案很少是您想要在实际应用中使用的。