STL Set/Map
Container | Implemented by | Order | Duplicatable | Modifiable | O(find) | Insertion/Deletion |
---|---|---|---|---|---|---|
set / map | Red Black Tree | Ordered | No | No | O(logn) | O(logn) |
multiset / multimap | Red Black Tree | Ordered | Yes | No | O(logn) | O(logn) |
unordered_set / unordered_map | Hash Table | Unorderd | No | No | O(1) | O(1) |
242.Valid Anagram
Limited possiblities(26 character) => Use array int[]
- Counting numbers of elements for one words, and minusing the counts down when iterating characters of another word
- If any of the counters != 0, returns false
349.Intersection of Two Arrays
Limited possiblities(1 <= num <= 1000) => Use array
Only requiring the intersected numbers, not with the counters => bool[]
- Marking apperance of numbers as true
bucket[num] = true
from the first vector - Iterating the second vector, insert the num in the results if bool[num] is true, and mark the flag as false
bucket[num] = false
to prevent multi insertion
202.Happy Number
- Happy number will end up to 1
- Unhappy number will go into a loop
=> Slow And Fast Pointers
bool isHappy(int n)
{
int slow = n, fast = n;
do
{
fast = bitSquareSum(fast);
fast = bitSquareSum(fast);
slow = bitSquareSum(slow);
if(slow == 1)
return true;
}while(slow!=fast);
return false;
}
1. Two Sum
The Range of number is too large => Using unordered_map as bucket
unordered_map<int, int> bucket; // num -> index
for(int i = 0; i < nums.size(); ++i)
{
if(auto n =bucket.find(target - nums[i]); n != bucket.end())
return vector<int>{i, n->second};
bucket.emplace(nums[i], i);
}
return vector<int>();