![[LeetCode] Single Number III ( a New Questions Added today) [LeetCode] Single Number III ( a New Questions Added today)](https://image.shishitao.com:8440/aHR0cHM6Ly9ia3FzaW1nLmlrYWZhbi5jb20vdXBsb2FkL2NoYXRncHQtcy5wbmc%2FIQ%3D%3D.png?!?w=700)
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; }
}