非常感谢你阅读本文~
欢迎【点赞】【⭐收藏】【评论】~
放弃不难,但坚持一定很酷~
希望我们大家都能每天进步一点点~
本文由 二当家的白帽子 https://le-yi.blog.csdn.net/ 博客原创~
给你一个数组 items
,其中 items[i] = [typei, colori, namei]
,描述第 i
件物品的类型、颜色以及名称。
另给你一条由两个字符串 ruleKey
和 ruleValue
表示的检索规则。
如果第 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"] 未匹配检索规则。
class Solution {
public int countMatches(List<List<String>> items, String ruleKey, String ruleValue) {
// 类型转换可以根据类型的多少去考虑,如果多的话,肯定是hash表比较好
int type;
switch(ruleKey) {
case "type":
type = 0;
break;
case "color":
type = 1;
break;
default:
// name
type = 2;
break;
}
int ans = 0;
// 下面好像没有什么技巧
for (List<String> item : items) {
if (ruleValue.equals(item.get(type))) {
++ans;
}
}
return ans;
}
}
int countMatches(char *** items, int itemsSize, int* itemsColSize, char * ruleKey, char * ruleValue){
int type;
if (strcmp(ruleKey, "type") == 0) {
type = 0;
} else if (strcmp(ruleKey, "color") == 0) {
type = 1;
} else {
// name
type = 2;
}
int ans = 0;
// 下面好像没有什么技巧
for (int i = 0; i < itemsSize; ++i) {
if (strcmp(ruleValue, items[i][type]) == 0) {
++ans;
}
}
return ans;
}
class Solution {
public:
int countMatches(vector<vector<string>>& items, string ruleKey, string ruleValue) {
// 类型转换可以根据类型的多少去考虑,如果多的话,肯定是hash表比较好
int type;
if ("type" == ruleKey) {
type = 0;
} else if ("color" == ruleKey) {
type = 1;
} else {
// name
type = 2;
}
int ans = 0;
// 下面好像没有什么技巧
for (vector<string> &item : items) {
if (ruleValue == item[type]) {
++ans;
}
}
return ans;
}
};
class Solution:
def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:
if "type" == ruleKey:
types = 0
elif "color" == ruleKey:
types = 1
else:
types = 2
return sum(item[types] == ruleValue for item in items)
func countMatches(items [][]string, ruleKey string, ruleValue string) int {
// 类型转换可以根据类型的多少去考虑,如果多的话,肯定是hash表比较好
var types int
switch ruleKey {
case "type":
types = 0
case "color":
types = 1
default:
types = 2
}
ans := 0
// 下面好像没有什么技巧
for _, item := range items {
if ruleValue == item[types] {
ans++
}
}
return ans
}
impl Solution {
pub fn count_matches(items: Vec>, rule_key: String, rule_value: String) -> i32 {
let types = match rule_key.as_str() {
"type" => 0,
"color" => 1,
_ => 2
};
items.iter().filter(|item| {
rule_value == item[types]
}).count() as i32
}
}