Single Number II

来源:互联网 发布:java ee eclipse教程 编辑:程序博客网 时间:2024/05/21 06:11

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?

  1. //java里int始终占4个字节,32位,我们外层循环遍历32次,然后内层循环记录0-31位每一位出现的次数,  
  1. //内层循环结束后将结果取余于3即为当前位的值  
  2. //时间复杂度O(32 * n), 空间复杂度O(1)  
  3. // 比方说   
  4. //1101  
  5. //1101  
  6. //1101  
  7. //0011  
  8. //0011  
  9. //0011  
  10. //1010   这个unique的     
  11. //----  
  12. //4340  1的出现次数    
  13. //1010  余3的话 就是那个唯一的数!  
  14. public class Solution {  
  15.     public int singleNumber(int[] A) {  
  16.         int res=0;  
  17.         int bit;  
  18.         for(int j=0;j<32;j++){  
  19.             bit=0;  
  20.             for(int i=0;i<A.length;i++){  
  21.                 if((A[i]>>j&1)==1){  
  22.                     bit++;  
  23.                 }  
  24.             }  
  25.             bit=bit%3;  
  26.             res+=(1<<j)*bit;  
  27.         }         
  28.         return res;   
  29.     }  
  30. }  

0 0