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?
public class Solution {
public int[] singleNumber(int[] nums) {
// int res[] = new int[2];
// HashMap<Integer,Integer> m = new HashMap<>();
// for(int i=0;i<nums.length;i++)
// {
// if(m.containsKey(nums[i]))
// m.put(nums[i],m.get(nums[i])+1);
// else
// m.put(nums[i],1);
// }
// int i=0;
// for(Map.Entry<Integer,Integer> e:m.entrySet())
// {
// if(e.getValue()==1)
// res[i++] = e.getKey();
// }
// return res;
int res[] = new int[2];
int t = 0;
for(int i=0;i<nums.length;i++)
{
t^=nums[i];
}
int tem = t&(-t);
res[0] = 0;
res[1] = 0;
for(int i=0;i<nums.length;i++)
{
if((nums[i]&tem)==0)
res[0] ^=nums[i];
else
res[1] ^=nums[i];
}
return res;
}
}