一、题目
给你一个数组 items ,其中 items[i] = [typei, colori, namei] ,描述第 i 件物品的类型、颜色以及名称。
另给你一条由两个字符串 ruleKey 和 ruleValue 表示的检索规则。
如果第 i 件物品能满足下述条件之一,则认为该物品与给定的检索规则 匹配 :
ruleKey == "type" 且 ruleValue == typei 。
ruleKey == "color" 且 ruleValue == colori 。
ruleKey == "name" 且 ruleValue == namei 。
统计并返回 匹配检索规则的物品数量 。
来源:力扣
二、思路
数组items存放若干个物品特征的数组,ruleValue表示的是特征具体实例computer、phone等等,ruleKey表示的是索引,可以在程序之前将其转化为下标索引。然后依次遍历数组每一项与ruleKey、ruleValue做对比,若全符合条件count+1,最后输出count即为符合规则的物品数量。
三、代码
方法一:
class Solution:
def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:
count=0
if ruleKey=="type":
R=0
elif ruleKey=="color":
R=1
elif ruleKey=="name":
R=2
for i in items:
for m,k in enumerate(i) :
if k==ruleValue and m==R:
count += 1
return count
优化之后的:
class Solution:
def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:
count=0
if ruleKey=="type":
R=0
elif ruleKey=="color":
R=1
elif ruleKey=="name":
R=2
for i in items:
if i[R]==ruleValue:
count +=1
return count
方法二:
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)