LeetCode 每日一题:统计匹配检索规则的物品数量

176 阅读1分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第 19 天,点击查看活动详情

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

原题地址

给你一个数组 items ,其中 items[i] = [typei, colori, namei] ,描述第 i 件物品的类型、颜色以及名称。

另给你一条由两个字符串 ruleKeyruleValue 表示的检索规则。

如果第 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 <=10410^4
  • 1 <= typei.length, color_i.length, namei.length, ruleValue.length <= 10
  • ruleKey 等于 "type""color""name"
  • 所有字符串仅由小写字母组成

思路分析

  1. 题目中 items 里面存储的是 第i件 物品的类型、颜色及名称;
  2. 因此可以使用一个 map 来存储所有物品的类型 type、颜色 color 以及名称 name
  3. 按照 ruleKeymap 中来获取物品需要使用哪种属性来匹配,使用 filter 属性过滤出满足 ruleValue 的数组;
  4. 然后返回数组的长度即可。

AC 代码

/**
 * @param {string[][]} items
 * @param {string} ruleKey
 * @param {string} ruleValue
 * @return {number}
 */
var countMatches = function(items, ruleKey, ruleValue) {
    const map = {
        type: [],
        color: [],
        name: []
    }
    for(let i = 0; i < items.length; i++) {
        const item = items[i]
        map.type.push(item[0])
        map.color.push(item[1])
        map.name.push(item[2])
    }
    const res = map[ruleKey].filter(item => item === ruleValue)
    return res.length

};

结果:

  • 执行结果: 通过
  • 执行用时:84 ms, 在所有 JavaScript 提交中击败了22.83%的用户
  • 内存消耗:46.4 MB, 在所有 JavaScript 提交中击败了5.43%的用户
  • 通过测试用例:92 / 92

END