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位的数result的每一位记录所有数在这一位出现的次数,如果是3的倍数则消去,最后留下来的数则是所要的结果。

注意,result需要定义为unsigned int类型,否则会出现负数的情况。

 1     int singleNumber(int A[], int n) {
 2         // Note: The Solution object is instantiated only once and is reused by each test case.
 3         unsigned int result = 0, MASK;
 4         int i, j, tmp;
 5         for(i = 0; i < 32; i++){
 6             MASK = 1<<i;
 7             tmp = 0;
 8             for(j = 0; j < n; j++){
 9                 tmp += ((A[j]&MASK) > 0 ? 1:0);
10             }
11             result |= ((tmp%3)>0 ? MASK:0);
12         }
13         return result;
14     }

 

posted on 2013-10-10 18:22  waruzhi  阅读(267)  评论(0编辑  收藏  举报

导航