[594. Longest Harmonious Subsequence] C++, using unordered_map


  • 0
    class Solution {
    public:
    int findLHS(vector<int>& nums) {
        if(nums.size() < 2) return 0;
        unordered_map<int,int> mp;
        for(auto num : nums){
            mp[num]++;
        }
        int res = 0, i = 0;
        while(i < nums.size()){
            if(mp.find(nums[i]) != mp.end()){
                if(mp.find(nums[i] + 1) != mp.end()){
                    res = max(res, mp[nums[i]+1] + mp[nums[i]]);
                }
                if(mp.find(nums[i] - 1) != mp.end()){
                    res = max(res, mp[nums[i]-1] + mp[nums[i]]);
                }
                mp.erase(nums[i]);
            }
            i++;
        }
        return res;
    }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.