题目:
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.
解释:
由于是subsequence,所以可以随便抽选,找到合起来个数最多的两个数字即可,subsequence的长度就是这两个数字个数的总和。
python代码:
import collections
class Solution(object):
def findLHS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
count =collections.Counter(nums)
max_len=0
for x in count:
if x+1 in count:
max_len=max(max_len,count[x]+count[x+1])
return max_len
#include <map>
using namespace std;
class Solution {
public:
int findLHS(vector<int>& nums) {
map<int ,int >_map;
for (auto num:nums)
_map[num]++;
int max_len=0;
for(auto& item:_map)
{
if(_map.count(item.first+1))
max_len=max(max_len,_map[item.first]+_map[item.first+1]);
}
return max_len;
}
};
总结:
合理使用字典,恩