Single Number II
LeetCode #137 · Medium · Math · C++ solution with worked-out approach and complexity analysis.
Approach
Hash Map with Count Tracking
Strategy
- 1Use a map to count occurrences of each number.
- 2When a number appears once, add it with count 1.
- 3When it appears twice, increment count to 2.
- 4When it appears three times, remove it from the map.
- 5The remaining element in the map is the single number.
Time
O(n)
Space
O(n/3)
= O(n)
Problem description(from LeetCode)
Given an integer array nums where every element appears 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.
Examples
Example 1
- Input:
- nums = [2,2,3,2]
- Output:
- 3
Constraints
- •1 <= nums.length <= 3 * 10^4
- •-2^31 <= nums[i] <= 2^31 - 1
- •Each element in nums appears exactly three times except for one element which appears once.
C++ Solution
solution.cpp
class Solution {
public:
int singleNumber(vector<int> &nums) {
unordered_map<int, int> mp;
for (int num : nums) {
if (!mp[num]) {
mp[num] = 1;
} else if (mp[num] == 1) {
mp[num]++;
} else {
mp.erase(num);
}
}
return mp.begin()->first;
}
};