LeetCode – 350. Intersection of Two Arrays II


Given two arrays, write a function to compute their intersection.

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

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?

This problem can be solved by using a hashmap to store the count of each number.

public class Solution { public int[] intersect(int[] nums1, int[] nums2) { HashMap map = new HashMap(); ArrayList list = new ArrayList(); for(int i=0;i integers){ int[] ret = new int[integers.size()]; for (int i=0; i < ret.length; i++) { ret[i] = integers.get(i).intValue(); } return ret; } }

This siteOriginal articleAll follow "Attribution-NonCommercial-ShareAlike 4.0 License (CC BY-NC-SA 4.0)Please retain the following annotations when sharing or adapting:

Original author:Jake Tao,source:"LeetCode – 350. Intersection of Two Arrays II"

139
0 0 139

Further Reading

Post a reply

Log inYou can only comment after that.
Share this page
Back to top