和谐数组是指一个数组里元素的最大值和最小值之间的差别正好是1。
现在,给定一个整数数组,你需要在所有可能的子序列中找到最长的和谐子序列的长度。
示例 1:
输入: [1,3,2,2,5,2,3,7]
输出: 5
原因: 最长的和谐数组是:[3,2,2,2,3].
说明: 输入的数组长度最大不超过20,000.
解题思路:用O(n)时间复杂度来实现,首先遍历一次数组,用map记录数字和出现的次数。然后遍历map,判断当前数字的前一个出现的次数和后一个出现的次数哪个大,然后加上当前数字出现的次数,最后得到结果。
class Solution {
public:
int findLHS(vector<int>& nums) {
unordered_map<int, int> m;
int res = 0;
for (auto i : nums)
m[i]++;
for (auto p : m)
{
int tmp = 0;
if (m.count(p.first + 1) > 0)
tmp = m[p.first + 1];
if (m.count(p.first - 1) > 0)
tmp = max(tmp, m[p.first - 1]);
if (tmp > 0)
res = max(res, p.second + tmp);
}
return res;
}
};