LeetCode探索(165):1773-统计匹配检索规则的物品数量

120 阅读1分钟

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

题目

给你一个数组 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 <= 10^4
  • 1 <= typei.length, colori.length, namei.length, ruleValue.length <= 10
  • ruleKey 等于 "type""color""name"
  • 所有字符串仅由小写字母组成

思考

本题难度简单。

首先是读懂题意。题目中输入一个二维数组 items、 字符串 ruleKey 以及 ruleValue,其中 items[i] = [typei, colori, namei] ,描述第 i 件物品的类型、颜色以及名称。需要从 items 找到满足条件的 ruleKey 和 ruleValue的,并返回其数量。

很简单的题目,我们可以使用模拟的方法。首先根据 ruleKey 判断是对应数组元素的哪个索引。接着,遍历数组 items,找出对应索引的数值是 ruleValue 的数组元素,最终返回满足条件的数量即可。

解答

方法一:模拟

/**
 * @param {string[][]} items
 * @param {string} ruleKey
 * @param {string} ruleValue
 * @return {number}
 */
var countMatches = function(items, ruleKey, ruleValue) {
  let index = 0
  if (ruleKey === 'type') {
    index = 0
  } else if (ruleKey === 'color') {
    index = 1
  } else {
    index = 2
  }
  let num = 0
  items.forEach(item => {
    if (item[index] === ruleValue) {
      num++
    }
  })
  return num
}
// 执行用时:76 ms, 在所有 JavaScript 提交中击败了60.87%的用户
// 内存消耗:44.6 MB, 在所有 JavaScript 提交中击败了92.39%的用户
// 通过测试用例:92 / 92

复杂度分析:

  • 时间复杂度:O(n),其中 n 是输入 items 的长度。需要遍历一遍 items。
  • 空间复杂度:O(1)。

参考