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

71 阅读2分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第11天,点击查看活动详情

题目 leetcode.cn/

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

  • 另给你一条由两个字符串 ruleKey 和 ruleValue 表示的检索规则。

  • 如果第 i 件物品能满足下述条件之一,则认为该物品与给定的检索规则 匹配 :

    • ruleKey == "type" 且 ruleValue == typei 。
    • ruleKey == "color" 且 ruleValue == colori 。
    • ruleKey == "name" 且 ruleValue == namei 。
  • 统计并返回 匹配检索规则的物品数量 。

示例

  • 输入: items = [["phone","blue","pixel"],["computer","silver","lenovo"],["phone","gold","iphone"]], ruleKey = "color", ruleValue = "silver"

    • 输出: 1
    • 解释: 只有一件物品匹配检索规则,这件物品是 ["computer","silver","lenovo"]
  • 输入: 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 <= item.length <= 100000
  • 1 <= typei.length,colori.length,namei.length,ruleValue.length <= 10
  • ruleKey等于"type""color"或者"name"
  • 所有字符串仅由小写字母构成

代码

function countMatches(items: string[][], ruleKey: string, ruleValue: string): number {
    let result = 0;
    for(let i = 0; i < items.length; i++){
        if(ruleKey === 'type'){
            if(items[i][0] === ruleValue){
                result++;
            }
        }else if(ruleKey === 'color'){
            if(items[i][1] === ruleValue){
                result++;
            }
        }else{
            if(items[i][2] === ruleValue){
                result++;
            }
        }
    }
    return result;
};

思路

  • 匹配检索,其实跟平常请求的时候传的query参数差不多,ruleKeyruleValue对应的?key=value

  • 所以只需要遍历找出传入的ruleKey对应的value就行

    • 一种是先遍历,再判断你传入的ruleKey是什么,统计符合条件的个数,这样每次都会判断一次,增加了时间成本
    • 另一种先判断你传入的ruleKey是什么,再循环遍历,统计个数,这样只需要判断一次,因为每次传入的ruleKey是固定的,所以不需要每次都判断,降低时间成本
  • 第二种写法

function countMatches(items: string[][], ruleKey: string, ruleValue: string): number {
    let result = 0;
    if(ruleKey === 'type'){
        for(let i = 0; i < items.length; i++){
            if(items[i][0] === ruleValue){
                result++;
            }
        }
    } else if(ruleKey === 'color'){
        for(let i = 0; i < items.length; i++){
            if(items[i][1] === ruleValue){
                result++;
            }
        }
    }else {
        for(let i = 0; i < items.length; i++){
            if(items[i][2] === ruleValue){
                result++;
            }
        }
    }
    return result;
};