LeetCode刷题之1773. Count Items Matching a Rule

1.Description

You are given an array items, where each items[i] = [typei, colori, namei] describes the type, color, and name of the ith item. You are also given a rule represented by two strings, ruleKey and ruleValue.

The ith item is said to match the rule if one of the following is true:

  • ruleKey == “type” and ruleValue == typei.
  • ruleKey == “color” and ruleValue == colori.
  • ruleKey == “name” and ruleValue == namei.

Return the number of items that match the given rule.

2.Test Cases

Example 1:

Input: items = [["phone","blue","pixel"],["computer","silver","lenovo"],["phone","gold","iphone"]], ruleKey = "color", ruleValue = "silver"
Output: 1
Explanation: There is only one item matching the given rule, which is ["computer","silver","lenovo"].

Example 2:

Input: items = [["phone","blue","pixel"],["computer","silver","phone"],["phone","gold","iphone"]], ruleKey = "type", ruleValue = "phone"
Output: 2
Explanation: There are only two items matching the given rule, which are ["phone","blue","pixel"] and ["phone","gold","iphone"]. Note that the item ["computer","silver","phone"] does not match.

3.Solution

3.1

这里的type,color和name没有定义好,所以需要自己组织,把它方法哦map中,让其value为list的下标取数据。

class Solution {
    public int countMatches(List<List<String>> items, String ruleKey, String ruleValue) {
        Map< String, Integer> rules = new HashMap<>();
        rules.put("type", 0);
        rules.put("color", 1);
        rules.put("name", 2);
        
        int key = rules.get(ruleKey);
        int count = 0;
        
        for (List<String> list : items) {
            if (ruleValue.equals(list.get(key)))
                count++;
        }
        return  count;
    }
}

3.2

用Lambda表达式,但是效率降低了。

class Solution {
    public int countMatches(List<List<String>> items, String ruleKey, String ruleValue) {
       Map< String, Integer> rules = new HashMap<>();
        rules.put("type", 0);
        rules.put("color", 1);
        rules.put("name", 2);

        int key = rules.get(ruleKey);

        long count1 = items.stream().filter(list -> {
            return ruleValue.equals(list.get(key));
        }).count();

        return  (int)count1;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值