Determine if one array contains all elements of another array

前端 未结 8 1881
闹比i
闹比i 2021-02-07 12:05

I need to tell if an array contains all of the elements of another array with duplicates.

[1,2,3].contains_all? [1,2]   #=> true
[1,2,3].contains_all         


        
8条回答
  •  心在旅途
    2021-02-07 12:33

    This solution will only iterate through both lists once, and hence run in linear time. It might however be too much overhead if the lists are expected to be very small.

      class Array
        def contains_all?(other)
          return false if other.size > size
          elem_counts = other.each_with_object(Hash.new(0)) { |elem,hash| hash[elem] += 1 }
          each do |elem|
            elem_counts.delete(elem) if (elem_counts[elem] -= 1) <= 0
            return true if elem_counts.empty?
          end
          false
        end
      end
    

提交回复
热议问题