C++ simple and short O(n) solution

  • 0
        int findLHS(vector<int>& nums) {
            int res=0, a=0, b=0, temp=0;
            unordered_map<int, int> m;
            for(int i=0;i<nums.size();i++) m[nums[i]]++;
            for(unordered_map<int, int>::iterator p=m.begin();p!=m.end();p++) {
                if(m.find(p->first+1)!=m.end()) a=m[p->first+1]; 
                if(m.find(p->first-1)!=m.end()) b=m[p->first-1]; 
                temp=max(a, b);
                if(temp!=0) res=max(res, p->second+temp);
                a=0, b=0;
            return res;

Log in to reply

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