题目要求:
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;
}
};
本文介绍了一种线性时间复杂度的算法,用于从每个元素都出现三次的整数数组中找出仅出现一次的整数。通过统计每一位上1出现的次数,并判断是否能被3整除来确定目标整数的每一位。
920

被折叠的 条评论
为什么被折叠?



