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?
"we notice that A and B must be different at some bit at position t in their binary representations. So if we divide the set of numbers into 2 set, one is the set of all the numbers that have the same bit at position t as A, the other is the set of all numbers that have the same bit at position t as B. These 2 sub-sets have a special characteristic: all numbers appear 2 times, except 1. This bring us to the Single Number problem."
Reference: http://traceformula.blogspot.com/2015/09/single-number-iii-leetcode.html
public class Solution { public int[] singleNumber(int[] nums) { int A = 0; int B = 0; int AXORB = 0; for (int n : nums) { AXORB ^= n; } int lastBit = (AXORB & (AXORB - 1)) ^ AXORB; // find the last bit that A differs from B for (int n : nums) { // based on the last bit, group the items into groupA (include A) and groupB if ((lastBit & n) == 0) { A ^= n; } else { B ^= n; } } return new int[]{A, B}; } }
No comments:
Post a Comment