很简洁的几个答案
594 Longest Harmonious Subsequence
class Solution {
public:
int findLHS(vector<int>& nums) {
int res = 0;
map<int, int> m;
for (int num : nums) ++m[num];
for (auto a : m) {
if (m.count(a.first + 1)) {
res = max(res, m[a.first] + m[a.first + 1]);
}
}
return res;
}
};
575 Distribute Candies
class Solution {
public:
int distributeCandies(vector<int>& candies) {
unordered_set<int> candyType(candies.begin(), candies.end());
return min(candyType.size(),candies.size() / 2);
}
};
总结
unordered_map <类型1,类型2> hash; //哈希表数据类型
vector.push_back() //增加新元素
find(vec.begin(),vec.end(),value) != vec.end(); //判断vec中存在value元素