本文共 857 字,大约阅读时间需要 2 分钟。
给你一个数组 items ,其中 items[i] = [typei, colori, namei] ,描述第 i 件物品的类型、颜色以及名称。
另给你一条由两个字符串 ruleKey 和 ruleValue 表示的检索规则。
如果第 i 件物品能满足下述条件之一,则认为该物品与给定的检索规则 匹配 :
ruleKey == “type” 且 ruleValue == typei 。
ruleKey == “color” 且 ruleValue == colori 。 ruleKey == “name” 且 ruleValue == namei 。 统计并返回匹配检索规则的物品数量。简单地遍历即可。可以使用哈希表存储ruleKey和列索引的映射,避免每次都进行判断。
class Solution { public: 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; }};
转载地址:http://hoxj.baihongyu.com/