持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第13天,点击查看活动详情
1773. 统计匹配检索规则的物品数量
难度:简单
题目:
给你一个数组 items ,其中 items[i] = [typei, colori, namei] ,描述第 i 件物品的类型、颜色以及名称。
另给你一条由两个字符串 ruleKey 和 ruleValue 表示的检索规则。
如果第 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 <= 1041 <= typei.length, colori.length, namei.length, ruleValue.length <= 10ruleKey等于"type"、"color"或"name"- 所有字符串仅由小写字母组成
个人思路
1.模拟
根据题意利用哈希表将rulekey转成转换为 item[i]的下标,然后再遍历一遍items,返回结果
class Solution {
public:
int countMatches(vector<vector<string>>& items, string ruleKey, string ruleValue) {
unordered_map<string, int> dictionary = {{"type", 0}, {"color", 1}, {"name", 2}};
int res = 0, index = dictionary[ruleKey];
for (auto &&item : items) {
if (item[index] == ruleValue) {
res++;
}
}
return res;
}
};
备注: map和unordered_map都是c++中可以充当字典(key-value)来用的数据类型,但是其基本实现是不一样的。
对于map的底层原理,是通过红黑树(一种非严格意义上的平衡二叉树)来实现的,因此map内部所有的数据都是有序的,map的查询、插入、删除操作的时间复杂度都是O(logn)。此外,map的key需要定义operator <,对于一般的数据类型已被系统实现,若是用户自定义的数据类型,则要重新定义该操作符。
unordered_map和map类似,都是存储的key-value的值,可以通过key快速索引到value。不同的是unordered_map不会根据key的大小进行排序,存储时是根据key的hash值判断元素是否相同,即unordered_map内部元素是无序的。unordered_map的底层是一个防冗余的哈希表(开链法避免地址冲突)。unordered_map的key需要定义hash_value函数并且重载operator ==。
哈希表最大的优点,就是把数据的存储和查找消耗的时间大大降低,时间复杂度为O(1);而代价仅仅是消耗比较多的内存。哈希表的查询时间虽然是O(1),但是并不是unordered_map查询时间一定比map短,因为实际情况中还要考虑到数据量,而且unordered_map的hash函数的构造速度也没那么快,所以不能一概而论,应该具体情况具体分析。
每天记录一下做题思路。