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].
一刷没ac
解题思路:和出现一次的数一样用了异或的性质,技巧在于先讲两个出现一次的异或计算出,然后找到第一个或者最后一个1,然后用这个特点对数组进行分组。
public class Solution {
public int[] singleNumber(int[] nums) {
int[] res = new int[2];
if(nums == null || nums.length < 2) return res;
int tmp = 0;
for(int i : nums){
tmp ^= i;
}
tmp &= -tmp;
for(int i : nums){
if((tmp & i) == 0) res[0] ^= i;
else res[1] ^= i;
}
return res;
}
}
public class Solution {
public int[] singleNumber(int[] nums) {
int[] res = new int[2];
if(nums == null || nums.length < 2) return res;
int tmp = 0;
for(int i : nums){
tmp ^= i;
}
tmp = Integer.highestOneBit(tmp);
for(int i : nums){
if((tmp & i) == 0) res[0] ^= i;
else res[1] ^= i;
}
return res;
}
}