Given 2*n + 2
numbers, every numbers occurs twice except two, find them.
Example
Given [1,2,2,3,4,4,5,3]
return 1
and 5
Challenge
O(n) time, O(1) extra space.
public class Solution { /** * @param A : An integer array * @return : Two integers */ public List<Integer> singleNumberIII(int[] A) { // write your code here if(A == null || A.length == 0) return new ArrayList<Integer>(); List<Integer> res = new ArrayList<Integer>(); int temp = A[0]; for(int i = 1; i < A.length; i++) temp ^= A[i]; int index = 0; for(int i = 0; i < 32; i++){ if(((temp >> i) & 1) == 1){ index = i; break; } } Integer res1 = null; Integer res2 = null; for(int i = 0; i < A.length; i++){ if(((A[i] >> index) & 1) == 1){ if(res1 == null){ res1 = A[i]; } else{ res1 ^= A[i]; } } else{ if(res2 == null){ res2 = A[i]; } else{ res2 ^= A[i]; } } } res.add(res1); res.add(res2); return res; } }
时间: 2024-12-27 10:49:00