本文共 795 字,大约阅读时间需要 2 分钟。
为了解决这个问题,我们需要统计给定数组中的物品数量,使其满足特定的检索规则。检索规则可以是物品的类型、颜色或名称中的任意一个。我们可以通过遍历数组并使用哈希表来优化查找过程。
这种方法的时间复杂度为O(n),其中n是物品的数量,确保了高效性。
#include#include #include using namespace std;int countMatches(vector > items, string ruleKey, string ruleValue) { unordered_map mp; mp["type"] = 0; mp["color"] = 1; mp["name"] = 2; int res = 0; for (int i = 0; i < items.size(); ++i) { if (items[i][mp[ruleKey]] == ruleValue) { res++; } } return res; }
unordered_map<string, int> mp存储了规则关键字及其对应的索引位置。res加一。这种方法确保了在处理大量物品时的高效性和准确性。
转载地址:http://hoxj.baihongyu.com/