Description
https://leetcode.com/problems/single-number-iii/
题目大意:
给定一个数组,所有元素都出现两次,除了两个元素只出现一次,找出这两个只出现一次的元素。要求时间复杂度O(n),空间复杂度O(1)。
Solving Ideas
https://blog.csdn.net/qq_32767041/article/details/83831330#615__2793
Solution
class Solution {
public int[] singleNumber(int[] nums) {
if (nums == null || nums.length < 2) return null;
//1.get xor result
int xorRes = 0;
for (int num : nums) xorRes ^= num;
//2.find the first bit from xorRes which is 1
int offset = 0;
while ((xorRes >>>= 1) != 0) offset++;
//3.divide the array into two subarrays logically
int[] res = new int[2];
for (int num : nums) {
if ((num >>> offset & 1) == 1) res[0] ^= num;
else res[1] ^= num;
}
return res;
}
}