题目:
Given an array of integers, every element appears three times except for one. Find that single one.
解答:
如果是挑出非偶数次数的元素,可以利用每个元素依次异或的方法。但是非奇数次数(3,5,7,9……)的元素?
如果要快,可以hash_map存储。然后遍历一遍hash_map找到Single Number。
换种思路,按位找不同的Single Number对应的位。细节上:
class Solution {
public:
int singleNumber(int A[], int n) {
int bit, bitsum;
int ans;
for(int i = 0; i < 32; i++)
{
bit = 1 << i;
bitsum = 0;
for(int j = 0; j < n; j++)
{
if(bit & A[j]) bitsum++;
}
if(bitsum % 3) ans = ans | bit;
}
return ans;
}
};【LeetCode从零单刷】Single Number II
原文地址:http://blog.csdn.net/ironyoung/article/details/45690459