您的位置:首页 > 产品设计 > UI/UE

[LeetCode] Single Number III ( a New Questions Added today)

2015-08-17 15:49 127 查看
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?

这是今天刚加上去的一道题。

个人觉得这道题和之前single number的两道差不多。依旧用hashset即可做出。

唯一要注意的就是最后return的时候不能直接return hashset。为了偷懒我直接弄了个新的int[]。

代码如下。~

public class Solution {
public int[] singleNumber(int[] nums) {
if(nums.length==2&&nums[0]!=nums[1]){
return nums;
}

HashSet<Integer> store=new HashSet<Integer>();
HashSet<Integer> result=new HashSet<Integer>();
for(int i=0;i<nums.length;i++){
if(!result.add(nums[i])){
result.remove(nums[i]);
store.add(nums[i]);
}else{
if(store.contains(nums[i])){
result.remove(nums[i]);
}
}
}
int[] print=new int[2];
print[0]=result.iterator().next();
result.remove(result.iterator().next());
print[1]=result.iterator().next();
return print;

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: