Single Number II
Given an array of integers, every element appears three times except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
思路:
假设每一个整数都是由32个bit组成的。当我们把所有的数字的相应的bit加起来mod 3 所得到的是0或者是1取决于那个single number是0还是1.
1 public class Solution { 2 public int singleNumber(int[] A) { 3 if(A.length<3)return -1; 4 int bit=0; 5 int single_number=0; 6 for(int i=0;i<32;i++){ 7 for(int j=0; j<A.length; j++){ 8 bit=(bit+(A[j]>>i&1))%3; 9 } 10 single_number+=(bit<<i); 11 } 12 return single_number; 13 } 14 }