C++ Frequency Map Solution


  • 0
    H
    int findLHS(vector<int>& nums) {
        int n = nums.size();
        if(n == 0) return 0;
        int maxlen = INT_MIN;
        
        map<int, int> map;
        
        for(int i = 0; i < n; i++) map[nums[i]]++;
        
        for(auto it = map.begin(); it != map.end(); it++){
            int temp = 0;
            if(next(it, 1) != map.end() && next(it, 1)->first - it->first <= 1){
                temp = next(it, 1)->second;
                temp += it->second;
                maxlen = max(maxlen, temp);
            }
        }
        
        return maxlen < 0 ? 0: maxlen;
    }

  • 0
    J

    @hu20
    Nice!
    The key insight is that, even though this problem asks for "subsequence", there is really little to do with ordering.


  • 0
    H

    Exact!exactexact


Log in to reply
 

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