Intersection of two arrays

Posted on

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

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

Note:

  • Each element in the result must be unique.
  • The result can be in any order.
public int[] intersection(int[] nums1, int[] nums2) {    public int[] intersection(int[] nums1, int[] nums2) {        if (nums1 == null || nums2 == null) return null; Set<Integer> array = new HashSet<Integer>(); Set<Integer> common = new HashSet<Integer>();
for (int i = 0; i < nums1.length; i++) { array.add(nums1[i]); }
for (int j = 0; j < nums2.length; j++) { if (array.contains(nums2[j])) { common.add(nums2[j]); } }
int[] result = new int[common.size()]; int k = 0; for (int integer : common) { result[k] = integer; k += 1; } return result;
}

Use HashSet to reduce the complexity to O(m+n).

Get familiar with basic set operations, add, contains and iteration.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s