给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。
说明:
你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?
方法一:使用HashMap
时间复杂度:O(N)
空间复杂度:O(N)
class Solution {
public int singleNumber(int[] nums) {
Map<Integer, Integer> map = new HashMap<>();
for(int num : nums){
if(map.containsKey(num))
map.put(num, map.get(num) + 1);
else map.put(num, 1);
}
for(Integer i : map.keySet()){
int count = map.get(i);
if(count == 1) return i;
}
return -1;
}
}
使用异或方法
时间复杂度:O(N)
空间复杂度:O(1)
class Solution {
public int singleNumber(int[] nums) {
int single = 0;
for(int num : nums){
single ^= num;
}
return single;
}
}