O(MAX(M,N)) in Ruby


  • 0
    D
    def intersect(nums1, nums2)
      item_counts_1 = item_counts(nums1) # N1
      item_counts_2 = item_counts(nums2) # N2
      item_counts_1.flat_map { |k,v| [k] * [item_counts_2[k] || 0, v].min }
    end
    
    def item_counts(items)
      items.reduce({}) do |current, newVal|
        current.merge!({ newVal => 1 }) { |key, oldVal, newVal| oldVal + 1 }
      end
    end
    

Log in to reply
 

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