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.
分析
题目的意思是:找出数组里面最长的harmonious数组。
- 这道题要求两数相差不超过1的最大长度,由于C++的map有排序的功能,我们统计nums的值的频率,然后遍历找到符合harmonious要求的数组就行了。
代码
class Solution {
public:
int findLHS(vector<int>& nums) {
if(nums.empty()){
return 0;
}
map<int,int> m;
for(int i=0;i<nums.size();i++){
m[nums[i]]++;
}
int res=0;
for(auto it=next(m.begin());it!=m.end();it++){
auto pre=prev(it);
if(it->first==pre->first+1){
res=max(res,it->second+pre->second);
}
}
return res;
}
};