leetcode 350-Intersection of Two Arrays II

难度:easy

Example:
Given nums1 = [1, 2, 2, 1]nums2 = [2, 2], return [2, 2].

Note:

  • Each element in the result should appear as many times as it shows in both arrays.
  • The result can be in any order.

Follow up:

  • What if the given array is already sorted? How would you optimize your algorithm?
  • What if nums1's size is small compared to nums2's size? Which algorithm is better?
  • What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?

思路:本题需要注意的是:如果一个数比如2,如果在nums1中出现两次,在nums2中出现一次,那么2 return的次数是取较小值一次。不会优化,现阶段的水平能做出来,再多掌握几种算法套路,不超时就够了。

          方法1:最擅长的转dictionary方法,把nums1的element转化为dict的key,每个数出现的次数转化为对应key的value。然后再遍历nums2,找nums2中与dict的key相同的element。


leetcode 350-Intersection of Two Arrays II


方法2:借鉴别人的双指针法(two pointers),将两个list先sort,然后两个指针分别遍历两个list,如果相同,就是需要return的值,如果一个比一个大,让较小的element的指针向前走一步再进行比较。


leetcode 350-Intersection of Two Arrays II