*Single Number III
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?
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
1 /** 2 * 本代码由九章算法编辑提供。没有版权欢迎转发。 3 * - 九章算法致力于帮助更多中国人找到好的工作,教师团队均来自硅谷和国内的一线大公司在职工程师。 4 * - 现有的面试培训课程包括:九章算法班,系统设计班,BAT国内班 5 * - 更多详情请见官方网站:http://www.jiuzhang.com/ 6 */ 7 8 public class Solution { 9 /** 10 * @param A : An integer array 11 * @return : Two integers 12 */ 13 public List<Integer> singleNumberIII(int[] A) { 14 int xor = 0; 15 for (int i = 0; i < A.length; i++) { 16 xor ^= A[i]; 17 } 18 19 int lastBit = xor - (xor & (xor - 1)); 20 int group0 = 0, group1 = 0; 21 for (int i = 0; i < A.length; i++) { 22 if ((lastBit & A[i]) == 0) { 23 group0 ^= A[i]; 24 } else { 25 group1 ^= A[i]; 26 } 27 } 28 29 ArrayList<Integer> result = new ArrayList<Integer>(); 30 result.add(group0); 31 result.add(group1); 32 return result; 33 } 34 }