Python 119ms beats 99% submissions with explanation


  • 1
    A
    1. Just convert input array into a dictionary of elements.
    2. For each element in the dictionary, check if the next element exists, for ex: if dict contains key '2', check if there is a '3' in there
      If yes, then find the length of that subsequence using sum of no of elements of each type
      If not, proceed to next element
    3. Return the max
      Previously I had used Counter, this resulted in more time,
    
    class Solution(object):
        
        def findLHS(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            mp={}
            for i in nums:
                if i not in mp:
                    mp[i]=1
                else: mp[i]+=1
                
            ln=0;
            
            for i in mp:
                if mp.get(i+1):
                    ln=max(ln,mp[i]+mp[i+1])
            return ln     
            
    

  • 0
    H

    @ash.ps312 Very good, absolutely fast than using Counter.


  • 0

    This is interesting, it actually implemented a simple version of counter

    mp={}
    for i in nums:
      if i not in mp:
        mp[i]=1
      else: mp[i]+=1
    

    I feel it is faster because there are too many small test cases.


Log in to reply
 

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