Easy
题目描述
给你一个数组 items,其中 items[i] = [typei, colori, namei] 描述第 i 件物品的类型、颜色以及名称。
另给你一条由两个字符串 ruleKey 和 ruleValue 表示的检索规则。
如果第 i 件物品能满足下述条件之一,则认为该物品与给定的检索规则 匹配 :
ruleKey == "type"且ruleValue == typei。ruleKey == "color"且ruleValue == colori。ruleKey == "name"且ruleValue == namei。
统计并返回 匹配检索规则的物品数量 。
示例 1:
输入:items = [["phone","blue","pixel"],["computer","silver","lenovo"],["phone","gold","iphone"]], ruleKey = "color", ruleValue = "silver"
输出:1
解释:只有一件物品匹配检索规则,这件物品是 ["computer","silver","lenovo"] 。
示例 2:
输入:items = [["phone","blue","pixel"],["computer","silver","phone"],["phone","gold","iphone"]], ruleKey = "type", ruleValue = "phone"
输出:2
解释:只有两件物品匹配检索规则,这两件物品分别是 ["phone","blue","pixel"] 和 ["phone","gold","iphone"] 。注意,["computer","silver","phone"] 未匹配检索规则。
提示:
1 <= items.length <= 10^41 <= typei.length, colori.length, namei.length, ruleValue.length <= 10ruleKey等于"type"、"color"或"name"- 所有字符串仅由小写字母组成
解题思路
这是一道简单的数组遍历题目。我们需要根据给定的规则键和规则值,统计有多少个物品满足匹配条件。
解题思路:
直接遍历:遍历每个物品,根据
ruleKey确定要比较的属性索引,然后判断对应的值是否等于ruleValue。索引映射:可以使用哈希表将规则键映射到对应的索引位置,这样代码更简洁:
"type"对应索引 0"color"对应索引 1"name"对应索引 2
条件判断:也可以直接使用 if-else 语句判断规则键的类型。
推荐解法:使用索引映射的方法,代码简洁且易于理解。时间复杂度为 O(n),其中 n 是物品数量,空间复杂度为 O(1)。
对于每个物品,我们只需要检查对应规则键位置的值是否与规则值相等即可。
代码实现
class Solution {
public:
int countMatches(vector<vector<string>>& items, string ruleKey, string ruleValue) {
unordered_map<string, int> ruleMap = {{"type", 0}, {"color", 1}, {"name", 2}};
int index = ruleMap[ruleKey];
int count = 0;
for (const auto& item : items) {
if (item[index] == ruleValue) {
count++;
}
}
return count;
}
};
class Solution:
def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:
rule_map = {"type": 0, "color": 1, "name": 2}
index = rule_map[ruleKey]
return sum(1 for item in items if item[index] == ruleValue)
public class Solution {
public int CountMatches(IList<IList<string>> items, string ruleKey, string ruleValue) {
var ruleMap = new Dictionary<string, int> {
{"type", 0}, {"color", 1}, {"name", 2}
};
int index = ruleMap[ruleKey];
int count = 0;
foreach (var item in items) {
if (item[index] == ruleValue) {
count++;
}
}
return count;
}
}
var countMatches = function(items, ruleKey, ruleValue) {
const ruleMap = {"type": 0, "color": 1, "name": 2};
const index = ruleMap[ruleKey];
return items.reduce((count, item) => {
return item[index]
复杂度分析
| 复杂度类型 | 复杂度 | 说明 |
|---|---|---|
| 时间复杂度 | O(n) | 需要遍历所有 n 个物品 |
| 空间复杂度 | O(1) | 只使用常数级别的额外空间 |