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;
}
}
本文介绍了一种算法解决方案,用于计算给定数组中符合特定规则的元素数量。通过使用HashMap将属性映射到数组索引,该算法能高效地处理不同类型的匹配条件。

被折叠的 条评论
为什么被折叠?



