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:
[5, 3]
is also correct.
这是今天刚加上去的一道题。
个人觉得这道题和之前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; } }