您的位置:首页 > 其它

Leetcode 137: (Single Number II)

2016-04-13 20:20 447 查看
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的数组存贮每位中1出现的次数,由于除去要选择的那个数,其它的数都是出现三次,所以取完次数后%3,所得的结果就是唯一一个没有出现三次的那个数。

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