C has nothing native for hashmap We need to write one ourselves.
C++ has unordered_map which is implemented via hashing. We will discuss treemaps in C++ as well later, which in practice seem to behave faster in C++.
unordered_map<int, int> A; // declares an empty map. O(1)
A.insert({key, value}); // O(1) time on average
if (A.find(K) == A.end()) return null; // means that K does not exist in A.
else return A[K]; // O(1) average case. Rare worst case O(n).
A.size() // O(1)
if (A.find(K) != A.end()) A.erase(A.find(K));
OR A.erase(K);
Now we come to one of the most popular data structures in Java, HashMap.
HashMap<Integer, Integer> A = new HashMap<Integer, Integer>(); // declares an empty map.
A.put(key, value); // O(1) time on average
A.get(K) // null if the key K is not present
A.containsKey(K) tells if the key K is present.
// Both operations O(1) average time. O(n) rare worst case
A.size() // O(1)
A.remove(K);
Python has dictionaries which serve the same purpose.
A = {}
A[key] = value // O(1) average time. O(n) worst case
A[K] // O(1) average, O(n) worst
len(A) // O(1)
del A[K] // O(1) average, O(n) worst
Log In using