题目
给你一个数组 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 <= 104
- 1 <= typei.length, colori.length, namei.length, ruleValue.length <= 10
- ruleKey 等于 "type"、"color" 或 "name"
- 所有字符串仅由小写字母组成
解题思路
这是一道简单的匹配题,我们首先判断传进来的值是类型,是颜色还是名称,然后在数组中去遍历,去记录与之匹配成功的次数,最后累计起来返回出去,既然需要累计,那我们就用reduce这个方法来做我们遍历的方法
reduce参数(为不懂reduce参数做一下解释)
解题
/**
* @param {string[][]} items
* @param {string} ruleKey
* @param {string} ruleValue
* @return {number}
*/
var countMatches = function(items, ruleKey, ruleValue) {
// 首先我们知道我们需要匹配的顺序都是依次排列的,这样我们就可以通过[]取值的方法来做匹配
const map = {
type: 0,
color: 1,
name: 2,
}
//
return items.reduce((acc, curr) => {
// 匹配成功,个数加1
if(curr[map[ruleKey]] === ruleValue) {
acc ++
}
return acc;
},0) // 默认传递0
};
”本文正在参与「掘金 2021 春招闯关活动」, 点击查看 活动详情