LeetCode 594最长和谐子序列Easy
- 题目简述:和谐数组是指一个数组里元素的最大值和最小值之间的差别正好是1。现在,给定一个整数数组,你需要在所有可能的子序列中找到最长的和谐子序列的长度。
- 输入:[1,3,2,2,5,2,3,7] 输出:5 解释:最长的和谐数组是:[3,2,2,2,3].
- 思路:先用哈希表存储每个数字出现的次数,然后对于哈希表里面的每个键,查看是否存在(该键+1),如果存在,计算该和谐子序列是否为最长的序列。
class Solution {
public:
int findLHS(vector<int>& nums) {
if(nums.empty()) return 0;
unordered_map<int, int> hash;
for(auto num : nums) hash[num]++;
int ans = 0;
for(auto x : hash)
{
if(hash.count(x.first + 1))
ans = max(ans, x.second + hash[x.first + 1]);
}
return ans;
}
};
class Solution {
public:
int findLHS(vector<int>& nums) {
if(nums.empty()) return 0;
unordered_map<int, int> hash;
for(auto num : nums) hash[num]++;
int ans = 0;
for(auto x : hash)
{
unordered_map<int, int>::iterator it;
it = hash.find(x.first + 1);
if (it != hash.end())
ans = max(ans, x.second + it->second);
}
return ans;
}
};