594.Longest Harmonious Subsequence

594.Longest Harmonious Subsequence

难度:Easy

We define a harmounious array as 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.

采用hashMap统计每个数出现的次数,然后比较相邻两个数出现次数之和,求出最大值即可。

class Solution {
public:
    int findLHS(vector<int>& nums) {
        if(nums.empty()  || nums.size()==1) return 0;
        int res=0;
        unordered_map<int,int> cnt;
        for(int i=0;i<nums.size();i++)
            ++cnt[nums[i]];
        cout<<cnt.size()<<endl;
        for(auto start=cnt.begin();start!=cnt.end();start++)
        {
            if(cnt.count(start->first+1))
            res=max(res,start->second+cnt[start->first+1]);
            if(cnt.count(start->first-1))
            res=max(res,start->second+cnt[start->first-1]);
          //  cout<< res<<endl;
        }
        return res;
    }
};

执行用时 :116 ms, 在所有 C++ 提交中击败了80.28%的用户 内存消耗 :19.6 MB, 在所有 C++ 提交中击败了76.63%的用户

Last updated