0
点赞
收藏
分享

微信扫一扫

594. Longest Harmonious Subsequence*

594. Longest Harmonious Subsequence*

​​https://leetcode.com/problems/longest-harmonious-subsequence/description/​​

题目描述

We define a harmonious array is an array where the difference between its maximum value and its minimum value is exactly 1.

Now, given an integer array, you need to find the length of its longest harmonious subsequence among all its possible subsequences.

Example 1:

Input: [1,3,2,2,5,2,3,7]
Output: 5
Explanation: The longest harmonious subsequence is [3,2,2,2,3].

Note: The length of the input array will not exceed 20,000.

C++ 实现 1

使用查找表思路最为直观, 将元素在查找表中进行统计, 然后针对查找表中的每个元素 a, 判断 a + 1 是否存在于查找表中.

class Solution {
public:
int findLHS(vector<int>& nums) {
unordered_map<int, int> record;
for (auto &i : nums)
record[i] ++;
int res = 0;
for (auto iter : record)
if (record.count(iter.first + 1))
res = max(res, iter.second + record[iter.first + 1]);
return res;
}
};


举报

相关推荐

0 条评论