力扣(LeetCode)1773. 统计匹配检索规则的物品数量(C++)

一、环境说明

  1. 本文是 LeetCode1773. 统计匹配检索规则的物品数量。
  2. 模拟。
  3. 测试环境:Visual Studio 2019。

二、思路分析

直接匹配

朴素的思维模式是一次遍历:
简单匹配一下, r u l e K e y ruleKey ruleKey i t e m s items items的规则,规则匹配,再匹配属性。

hash表

直观的简化做法是hash思想:
建立一个 h a s h m a p hashmap hashmap,把 r u l e K e y ruleKey ruleKey映射为 i t e m item item对应属性的下标。题目给出 i t e m s [ i ] = [ t y p e i , c o l o r i , n a m e i ] items[i] = [typei, colori, namei] items[i]=[typei,colori,namei],我们要做的,就是把 t y p e 、 c o l o r 、 n a m e type、color、name typecolorname依次映射为 0 , 1 , 2 0,1,2 0,1,2。这一步帮我们省略了规则匹配,接下来只用匹配属性即可。

三、代码展示

直接匹配:

// 类型type 颜色color 名称name
class Solution {
public:
    int countMatches(vector<vector<string>>& items, string ruleKey, string ruleValue) {
        int ans = 0;
        for(int i =0;i<items.size();i++){
            if("color"==ruleKey){
                if(items[i][1]==ruleValue){
                    ans++;
                }//物品颜色
            }else if("type"==ruleKey){
                if(items[i][0]==ruleValue){
                    ans++;
                }
            }else{//name
                if(items[i][2]==ruleValue){
                    ans++;
                }
            }
        }
        return ans;
    }
};

哈希表:

class Solution {
public:
    int countMatches(vector<vector<string>>& items, string ruleKey, string ruleValue) {
        unordered_map<string,int> hash = {{"type",0},{"color",1},{"name",2}};
        int ans = 0,index = hash[ruleKey];
        for(auto x:items){
            if(x[index] == ruleValue) ans++;
        }
        return ans;
    }
};

四、博主致语

理解思路很重要!
欢迎读者在评论区留言,作为日更博主,看到就会回复的。

五、AC

AC
在这里插入图片描述

六、复杂度分析

  1. 时间复杂度: O ( n ) O(n) O(n) , n n n是物品数量。直接匹配和哈希表,都只进行一次遍历。时间复杂度是 O ( n ) O(n) O(n)
  2. 空间复杂度: O ( 1 ) O(1) O(1),除了若干变量使用的常量空间,没有使用额外的线性空间。特别的,本题 h a s h hash hash表也是常量级空间 ∣ C ∣ = 3 |C|=3 C=3
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

清墨韵染

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值