最直观的解法:
class Solution {
public:
int countMatches(vector<vector<string>>& items, string ruleKey, string ruleValue) {
int index = (ruleKey == "type")? 0 : (ruleKey == "color") ? 1: 2;
int res = 0;
for(int i = 0;i < items.size();i++)
{
if(items[i][index] == ruleValue)
res += 1;
}
return res;
}
};
运行效率:
Runtime: 72 ms, faster than 70.25% of C++ online submissions for Count Items Matching a Rule.
Memory Usage: 30.8 MB, less than 71.88% of C++ online submissions for Count Items Matching a Rule.
参考讨论区大神的的解法:
//#pragma GCC optimize ("Ofast,inline,omit-frame-pointer")
static auto x = []() {ios_base::sync_with_stdio(false); cin.tie(NULL); return NULL; }();
class Solution {
public:
int countMatches(vector<vector<string>>& items, string ruleKey, string ruleValue) {
int index = (ruleKey == "type")? 0 : (ruleKey == "color") ? 1: 2;
return count_if(items.begin(),items.end(),[&](const auto &i){return i[index] == ruleValue;});
}
};
运行效率:
Runtime: 60 ms, faster than 98.34% of C++ online submissions for Count Items Matching a Rule.
Memory Usage: 31.1 MB, less than 25.84% of C++ online submissions for Count Items Matching a Rule.
C++ lambda表达式和count_if配合使代码实现更加精炼和高效。