力扣打卡第七天 统计匹配检索规则的物品数量

统计匹配检索规则的物品数量

可以利用哈希表把输入 ruleKey\textit{ruleKey}ruleKey 转换为 items[i]\textit{items}[i]items[i] 的下标,然后再遍历一遍 items\textit{items}items,找出符合条件的物品数量。

复杂度分析

时间复杂度:O(n)O(n)O(n),其中 nnn 是输入 items\textit{items}items 的长度。需要遍历一遍 items

空间复杂度:O(1)O(1)O(1),仅消耗常数空间。

class Solution:
    def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:
        index = {"type": 0, "color": 1, "name": 2}[ruleKey]
        return sum(item[index] == ruleValue for item in items

猜你喜欢

转载自blog.csdn.net/qq_46157589/article/details/127584789