您的位置:首页 > 其它

LeetCode Single Number II

2014-03-03 16:38 246 查看
题目要求:

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?
解题思路:
对于n个整数,统计每位上出现1的次数;若能被3整除,说明要求的数在这一位为0,否则为1,从而得到要求的数。

代码实现:

class Solution {
public:
int singleNumber(int A[], int n) {
int bits[sizeof(int)*8] = {0};
int result = 0;
for(int i = 0; i < sizeof(int)*8; i++)
for(int j = 0; j <n; j++)
bits[i] +=((A[j] >> i) & 1);
for(int i = 0; i < sizeof(int)*8; i++)
if(bits[i] % 3)
result += (1 << i);
return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: