您的位置:首页 > 其它

【Leetcode】Single Number III

2015-12-01 10:56 351 查看
题目链接:https://leetcode.com/problems/single-number-iii/

题目:

Given an array of numbers
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:

Given
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]
is
also correct.
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: