您的位置:首页 > 编程语言 > C语言/C++

[leetcode] 【数组】 137. Single Number II

2016-05-30 10:32 260 查看
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?

题意

一个整数数组中,有一个元素只出现一次,其他每个元素都出现3次,找出这个元素。

题解

这里也是根据位的特性来处理,用于一个int所占bit数大小的数组count来存储二进制数的每一位。
把nums数组所有数都按位加在count数组中,然后对3求余,剩下的数就是只出现一次的数。

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