Single Number II leetcode java

题目:html

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? app

 

题解:spa

这题也用位运算,位运算反正我就很纠结很不熟。代码是网上找的,跟着debug外加别人讲才能明白点。.net

这道题算是single number的变形吧,可是由于是3个相同的数,因此操做并没那么简单了。debug

 

解题思想是:code

把每一位数都想成二进制的数,用一个32位的数组来记录每一位上面的1的count值。这里注意数组计数是从左往右走,而二进制数数是从右往左的。。因此数组第0位的count就是二进制最低位上的count的。例如:4的二进制是100(固然做为32位就是前面还一堆了000...000100这样子),3个4的话按照每位相加的话,按照二进制表示法考虑就是300,固然存在数组里面就是003(A[0]=0;A[1]=0;A[2]=3,而后后面到A[31]都得0)。
htm

 

而后对全部数按照二进制表示按位加好后,就要把他还原成所求的值。这里面的想法是,若是一个数字出现了3次,那么这个数字的每一位上面,若是有1那么累加确定是得3的,若是是0,天然仍是0。因此对每一位取余数,得的余数再拼接起来就是咱们要找的那个single one。blog

 

这里还原的方法是,对32位数组从0开始,对3取余数,由于数组0位置实际上是二进制的最低位,因此每次要向左移。用OR(|)和 + 均可以拼接回来。。three

 

代码以下:

 1  public  int singleNumber( int[] A) {  
 2           if(A.length == 0||A== null)  
 3              return 0;
 4         
 5          int[] cnt =  new  int[32];  
 6          for( int i = 0; i < A.length; i++){  
 7              for( int j = 0; j < 32; j++){  
 8                  if( (A[i]>>j & 1) ==1){  
 9                     cnt[j]++;  
10                 }  
11             }  
12         }  
13          int res = 0;  
14          for( int i = 0; i < 32; i++){  
15             res += (cnt[i]%3 << i);
16            // res |= (cnt[i]%3 << i);
17          }  
18         cnt =  null;  
19          return res;  
20     }

 同时还有一种更加看着简洁的代码表示,就是按照每一位对全部数字计算count(上面那个是对每个数计算每一位的count),这样就能够少用一个循环。。。

代码以下:

 1      public  int singleNumber( int[] A) {  
 2          int [] count =  new  int[32];
 3          int result = 0;
 4          for ( int i = 0; i < 32; i++) {
 5              for ( int j = 0; j < A.length; j++) {
 6                  if (((A[j] >> i) & 1)==1) {
 7                     count[i]++;
 8                 }
 9             }
10             result |= ((count[i] % 3) << i);
11         }
12          return result;
13     }

 

Reference:

http://blog.csdn.net/xiaozhuaixifu/article/details/12908869 http://www.acmerblog.com/leetcode-single-number-ii-5394.html

相关文章
相关标签/搜索