Given two arrays, write a function that determines if they are equal. bool AreEqual(vector<int> a, vector<int> b) { if (a.size() != b.size()) return false; // Since they are the same size if one is empty, they both are, hence equal if (a.empty()) return true; // Make a hash table of array a with elements being the key and value being number of times encountered hash_map<int, int> h; for (int e : a) h[e] = ('\0' == h[e]) ? 1 : h[e] + 1; // Iterate through array b and remove encountered elements for (int e : b) { // An element that wasn't added to the map or already removed, so immediately we know they aren't equal if ('\0' == h[e]) return false; h[e]--; // Remove the element when it hits zero so we would end up with an empty hash map if both arrays are equal if (0 == h[e]) h.erase(e); } if (!h.empty()) return false; return true; } |