【每日一题】:1773 统计匹配检索规则的物品数量

27 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第13天,点击查看活动详情

今天的每日一题是1773. 统计匹配检索规则的物品数量 - 力扣(LeetCode),这是一道简单的模拟题,根据题目的说明进行模拟就可以完成。但是需要注意的是这里需要用到常见的哈希表结构。

题目

给你一个数组 items ,其中 items[i] = [typei, colori, namei] ,描述第 i 件物品的类型、颜色以及名称。另给你一条由两个字符串 ruleKeyruleValue 表示的检索规则。

如果第 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"] 未匹配检索规则。

方法:

根据题目可以知道,题目主要是根据给定的商品按照条件进行检索,而不同的条件给出的搜索结果是不同的, 因此为了区别不同的搜索条件需要搜索的不同结果。我们可以定义HasMap结构来存储搜索条件搜索范围。如题所示在题目中分别有typecolorname。因此可以定义如下结构进行存储:

HashMap<String, Integer> map = new HashMap<String, Integer>() {{
            put("type", 0);
            put("color", 1);
            put("name", 2);
        }}

根据搜索条件到map中寻找结果,就可以得到最终搜索的位置,总体代码如下:

 public int countMatches(List<List<String>> items, String ruleKey, String ruleValue) {
    int index = new HashMap<String, Integer>() {{
        put("type", 0);
        put("color", 1);
        put("name", 2);
    }}.get(ruleKey);
    int res = 0;
    for (List<String> item : items) {
        if (item.get(index).equals(ruleValue)) {
            res++;
        }
    }
    return res;
}