题目链接
https://leetcode.cn/problems/count-items-matching-a-rule/
题目
我的思路
循环遍历外层List
如果ruleKey的值是type,那么取出每个List的第一个元素(下标为0的元素),并且比较与ruleValue的值是否相等,若相等,则计数加一;
如果ruleKey的值是color,那么取出每个List的第二个元素(下标为1的元素),并且比较与ruleValue的值是否相等,若相等,则计数加一;
如果ruleKey的值是name,那么取出每个List的第三个元素(下标为2的元素),并且比较与ruleValue的值是否相等,若相等,则计数加一;
import java.util.List;
class Solution {
public int countMatches(List<List<String>> items, String ruleKey, String ruleValue) {
int cnt = 0;
for (List<String> item : items) {
if ("type".equals(ruleKey)) {
if (item.get(0).equals(ruleValue)) {
cnt++;
}
} else if ("color".equals(ruleKey)) {
if (item.get(1).equals(ruleValue)) {
cnt++;
}
} else if ("name".equals(ruleKey)) {
if (item.get(2).equals(ruleValue)) {
cnt++;
}
}
}
return cnt;
}
}
官方思路
可以利用哈希表把输入ruleKey转换为items[i]的下标,然后再遍历一遍items,找出符合条件的物品数量
官方提供的代码要比我写的简洁许多,可以参考
import java.util.HashMap;
import java.util.List;
class Solution {
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 cnt = 0;
for (List<String> item : items) {
if (item.get(index).equals(ruleValue)) {
cnt++;
}
}
return cnt;
}
}