LeetCode 题解工作台
统计匹配检索规则的物品数量
给你一个数组 items ,其中 items[i] = [type i , color i , name i ] ,描述第 i 件物品的类型、颜色以及名称。 另给你一条由两个字符串 ruleKey 和 ruleValue 表示的检索规则。 如果第 i 件物品能满足下述条件之一,则认为该物品与给定的检…
2
题型
7
代码语言
3
相关题
当前训练重点
简单 · 数组·string
答案摘要
由于 `ruleKey` 只可能是 `"type"`、`"color"` 或 `"name"`,我们可以直接取 `ruleKey` 的第一个字符来确定 `item` 的下标 。然后遍历 `items` 数组,统计 `item[i] == ruleValue` 的个数即可。 时间复杂度 ,空间复杂度 。其中 为 `items` 的长度。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·string 题型思路
题目描述
给你一个数组 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 <= 1041 <= typei.length, colori.length, namei.length, ruleValue.length <= 10ruleKey等于"type"、"color"或"name"- 所有字符串仅由小写字母组成
解题思路
方法一:计数模拟
由于 ruleKey 只可能是 "type"、"color" 或 "name",我们可以直接取 ruleKey 的第一个字符来确定 item 的下标 。然后遍历 items 数组,统计 item[i] == ruleValue 的个数即可。
时间复杂度 ,空间复杂度 。其中 为 items 的长度。
class Solution:
def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:
i = 0 if ruleKey[0] == 't' else (1 if ruleKey[0] == 'c' else 2)
return sum(v[i] == ruleValue for v in items)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Candidate should understand how to iterate over arrays and conditionally check string values.
- question_mark
Look for the ability to optimize iterations, such as reducing unnecessary string comparisons.
- question_mark
See if the candidate can efficiently handle larger input sizes through improved algorithms.
常见陷阱
外企场景- error
Failing to properly match ruleKey to the correct index in the item array, leading to incorrect results.
- error
Not handling edge cases like empty arrays or rules that don't match any item.
- error
Unnecessarily complex solutions that don't take advantage of simple iteration for this problem.
进阶变体
外企场景- arrow_right_alt
What if the ruleKey is dynamic and changes per item, requiring different ruleKey checks for each one?
- arrow_right_alt
Consider a variant where you need to count multiple types of rules in one pass, instead of just one rule.
- arrow_right_alt
Change the input so that the ruleValue is not a string but a more complex data structure, like a range or set.