Leetcode 137. Single Number II
Given an integer array nums
where every element appears exactly three times except for one, which appears exactly once. Find the single element and return it.
You must implement a solution with a linear runtime complexity and use only constant extra space.
O(n)
) and uses only constant extra space (O(1)
).i
(from 0 to 31, considering the integer size), we’ll count how many times it appears across all numbers.#include <vector>
using namespace std;
class Solution {
public:
int singleNumber(vector<int>& nums) {
int bitCount[32] = {0};
for (int num : nums) {
for (int i = 0; i < 32; ++i) {
if (num & (1 << i)) {
bitCount[i]++;
}
}
}
int result = 0;
for (int i = 0; i < 32; ++i) {
if (bitCount[i] % 3) {
result |= (1 << i);
}
}
return result;
}
};
// Example
int main() {
vector<int> nums = {2, 2, 3, 2};
Solution sol;
int result = sol.singleNumber(nums);
// Output: 3
return 0;
}
The time complexity of this solution is O(n)
where n
is the number of elements in the input array. This is because we iterate through the array once and for each element, we perform a constant amount of work by iterating through 32 possible bit positions (which is a constant).
The space complexity is O(1)
, meaning it uses constant extra space, since our auxiliary space does not grow with the input size but remains fixed at 32 elements.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?