DEV Community

bengineer
bengineer

Posted on

LeetCode 350: Intersection of Two Arrays II (Ruby)

Description: https://leetcode.com/problems/intersection-of-two-arrays-ii/

Solution

def intersect(nums1, nums2)
    result = []
    shorter = nil
    longer = nil

    shorter, longer = [nums1, nums2].sort_by &:length

    shorter.uniq.each do |n|
        shorter_count = [longer.count(n), shorter.count(n)].min
        shorter_count.times do
            result << n
        end
    end
    result
end
Enter fullscreen mode Exit fullscreen mode

Bechmark

Runtime: 76 ms, faster than 28.69% of Ruby online submissions for Intersection of Two Arrays II.

Memory Usage: 209.9 MB, less than 91.80% of Ruby online submissions for Intersection of Two Arrays II.

Top comments (0)