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?
Solve it according to bits of different position, we thus need to verify the 32 bits. (suppose it is a 32-bit machine)
int singleNumber(vector<int>& nums) {
int target = 0;
for(int i = 0; i <= 31; ++i) {
int count = 0;
for(int j = 0; j < nums.size(); ++j) {
count = count + ((nums[j] >> i) & 0x1);
}
target = target | ((count % 3) << i);
}
return target;
}
Time Complexity is 32O(n). It can pass leetCode, not sure whether this is the most optimized solution though.
本文介绍了一种算法,用于从整数数组中找出仅出现一次的元素,而其他元素均出现三次。该算法利用位操作实现了线性时间复杂度,并且不使用额外内存,符合LeetCode的要求。

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



