Intersection of Two Arrays

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

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

 

Issues:

  1. Find the length of return int array.   -> use HashSet
  2. The numbers in the return array need to be unique. -> Convert HashSet into an array. 

 

 

public class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        Set<Integer> set = new HashSet<Integer>(); 
        Set<Integer> intersec = new HashSet<Integer>(); 
        //Add existing memeber of nums1 to set
        for (int i = 0; i < nums1.length; i++) {
            set.add(nums1[i]);
        }
        //Check the memeber of nums2 to see if it's contained in set
        for (int i = 0; i < nums2.length; i++) {
            if (set.contains(nums2[i])) {
                intersec.add(nums2[i]);
            }
        }
        //Convert HashSet to int array
        int[] result = new int[intersec.size()]; 
        //pay attention to the slightly different way of 
        //looping a HashSet
        int i = 0;
        for (Integer num: intersec) {
            result[i++] = num; 
        }
        return result; 
    }
}
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