一、环境说明
- 本文是 LeetCode1773. 统计匹配检索规则的物品数量。
- 模拟。
- 测试环境: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
type、color、name依次映射为
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
六、复杂度分析
- 时间复杂度: O ( n ) O(n) O(n) , n n n是物品数量。直接匹配和哈希表,都只进行一次遍历。时间复杂度是 O ( n ) O(n) O(n)。
- 空间复杂度: O ( 1 ) O(1) O(1),除了若干变量使用的常量空间,没有使用额外的线性空间。特别的,本题 h a s h hash hash表也是常量级空间 ∣ C ∣ = 3 |C|=3 ∣C∣=3。