Monday, July 22, 2019

C++ STL data structures for leetcode

vector

std::vector<string> v;
v.push_back(1);
v.pop_back(); // no return!
long size_ = v.size();

for (const )

Tips: use "auto" to avoid vector<int>::Iterator

vector<string>::Iterator it = v.begin();
for (auto it = v.begin(); it != v.end(); it++) {
string temp = *it;
}

or
for (int i : v) {
// i
}

or in a constant way.
for(auto const& value: v) { /* std::cout << value; ... */}

initialization
vector<int> vect{ 10, 20, 30 };
vector<int> vect(n, 10);
vector<unordered_map<int, int>> vect(n, {})


unordered_map
unordered_map<string, int> hash_map;
long size_ = hash_map.size();
unordered_*, so no way to do linear traversal. More usually use random access.
unordered_map<string, int>::iterator it;
(*it).first; //key
(*it).second; //value
hash_map[key] = value;

auto it = hash_map.find(key_);
if (it != hash_map.end()) {

}
or,
if (hash_map.count(key_)==1) { // do not allow multi value with same key, so only 1 or 0
}

Magic dynamic initialization
Every time call [] operator, unordered_map insert a default value if does not exist.
e.g.,
unordered_map<int, unordered_map<int, int>> dp;
without explicitly initialization, one can call dp[diff][j], and will return 0, this actually triggers initialization of inside unordered_map<int, int>, and the mapped value of it (int). Magic!
So, no need to explicitly check whether outside unordered_map has the key diff. I thought one has to do something like,
if (auto dp.find(diff) ==dp.end()) {
  unordered_map<int, int> empty;
  dp[diff] = empty;
}

Note: vector always costs less space than the hash_map, although they are at the same order (O(n)).

set
It is ordered!


TIP: To update the max length or count
res = max(res, dp[diff][i]);


 If simply needs a sort in C++, std::sort should be the standard way to do so, save your time, and reduce the length of code.









No comments:

Post a Comment