

思路:模拟
- 就、……、就、定位一下key,然后遍历每个相应的key找合法的值,定位key用哈希表定位或者条件运算符。
Java
哈希表
class Solution {
public int countMatches(List<List<String>> items, String ruleKey, String ruleValue) {
int rule = new HashMap<String, Integer>() {{
put("type", 0);
put("color", 1);
put("name", 2);
}}.get(ruleKey);
int res = 0;
for (var i : items) {
if (i.get(rule).equals(ruleValue))
res++;
}
return res;
}
}
条件运算符
class Solution {
public int countMatches(List<List<String>> items, String ruleKey, String ruleValue) {
int rule = ruleKey.charAt(0) == 't' ? 0 : ruleKey.charAt(0) == 'c' ? 1 : 2;
int res = 0;
for (var i : items) {
if (i.get(rule).equals(ruleValue))
res++;
}
return res;
}
}
- 时间复杂度:O(n)
- 空间复杂度:O(1)
C++
哈希表
class Solution {
public:
int countMatches(vector<vector<string>>& items, string ruleKey, string ruleValue) {
unordered_map<string, int> ruleDic = {{"type", 0}, {"color", 1}, {"name", 2}};
int rule = ruleDic[ruleKey], res = 0;
for (auto i : items) {
if (i[rule] == ruleValue)
res++;
}
return res;
}
};
条件运算符
class Solution {
public:
int countMatches(vector<vector<string>>& items, string ruleKey, string ruleValue) {
int rule = ruleKey[0] == 't' ? 0 : ruleKey[0] == 'c' ? 1 : 2;
int res = 0;
for (auto i : items) {
if (i[rule] == ruleValue)
res++;
}
return res;
}
};
- 时间复杂度:O(n)
- 空间复杂度:O(1)
Rust
- 把
match套在数组里就可以一行解决【为了好看还是分了个行】
- rust没有三目表达式,写个if-else还不如这个
impl Solution {
pub fn count_matches(items: Vec<Vec<String>>, rule_key: String, rule_value: String) -> i32 {
items.iter().fold(0, |res, i|
(i[match &rule_key as &str {"type" => 0, "color" => 1, "name" => 2, _=> 3}] == rule_value) as i32 + res)
}
}
- 时间复杂度:O(n)
- 空间复杂度:O(1)
总结