按要求操作即可
class Solution { private: unordered_map<int, int> HashSet; void CowHashSet() { HashSet.clear(); } void add(int id) { HashSet[id]++; } bool contains(int id) { return HashSet.count(id); } void remove(int id) { if (HashSet.count(id)) { HashSet.erase(id); } } public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param operations string字符串vector * @param args int整型vector<vector<>> * @return string字符串vector */ vector<string> manageCows(vector<string>& operations, vector<vector<int> >& args) { vector<string> ans; for (int i = 0; i < operations.size(); i++) { if (operations[i] == "CowHashSet") { CowHashSet(); ans.emplace_back("null"); } else if (operations[i] == "add") { add(args[i][0]); ans.emplace_back("null"); } else if (operations[i] == "contains") { if (contains(args[i][0])) { ans.emplace_back("true"); } else { ans.emplace_back("false"); } } else if (operations[i] == "remove") { remove(args[i][0]); ans.emplace_back("null"); } } return ans; } };
时间复杂度:哈希表单次插入:O(1),单次删除:O(1),单次查找:O(1)
空间复杂度:O(n),取决于要插入的数量