Simple C++ Hashmap, do traverse twice by for loop, O(n)


  • -1
    J

    class Solution {
    public:
    int findLHS(vector<int>& nums) {
    unordered_map<int,int> number;
    for(int i=0;i<nums.size();i++){
    int key=nums[i];
    number[key]++;
    }
    int maxn=0;
    for(auto it:number){
    int key=it.first;
    if(number.find(key+1)!=number.end()){maxn=max(maxn,number[key]+number[key+1]);}
    }
    return maxn;

    }
    

    };


Log in to reply
 

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