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?
Subscribe to see which companies asked this question
class Solution {
public:
int singleNumber(vector<int> &nums) {
int len = nums.size(), res = 0;
for(int i = 0; i < 32; i++) {
int cnt = 0;
for(int j = 0; j < len; j++) {
if((j >> i) & 1) cnt+=1;
}
if(cnt%3) {
res |= ((cnt%3) << i);
}
}
return res;
}
}
本文介绍了一种算法解决方案,用于找出一个整数数组中仅出现一次的元素,而其他元素都恰好出现三次。该算法实现了线性时间复杂度的要求,并且避免了使用额外的内存空间。
2611

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



