• 力扣(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;
        }
    };
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    哈希表:

    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;
        }
    };
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    四、博主致语

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

    五、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
  • 相关阅读:
    华为设备配置攻击溯源命令
    Linux用户和权限
    【已解决】ModuleNotFoundError: No module named sklearn
    Hive排序字段解析
    数据库第六章作业
    网络安全之python学习第二天
    【解决】多卡服务器GPU不能多用户同时使用的问题
    springboot实现项目启动前的一些操作
    更改当前动作路径为文件坐在地址路径,应对./这种情况,有利于项目移动
    Spark Core
  • 原文地址:https://blog.csdn.net/Innocence02/article/details/127582959