题目链接:https://leetcode.com/problems/single-number-iii/
题目:
nums
, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.
For example:
nums = [1, 2, 1, 3, 2, 5]
, return [3, 5]
.
Note:
- The order of the result is not important. So in the above example,
[5, 3]
- Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?
思路:
1、用HashMap,空间复杂度O(n)
2、用异或,具体参考百度。。我不会。。
算法1:
public int[] singleNumber(int[] nums) {
Map<Integer, Integer> maps = new HashMap<Integer, Integer>();
for (int i : nums) {
if (maps.containsKey(i)) {
maps.remove(i);
} else {
maps.put(i, 1);
}
}
Set<Integer> sets = maps.keySet();
Iterator<Integer> it =sets.iterator();
int []a = new int[sets.size()];
int i=0;
while(it.hasNext()){
a[i++] = it.next();
}
return a;
}