Saturday, October 21, 2017

349. 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].
Note:
  • Each element in the result must be unique.
  • The result can be in any order.

Solution:
Use a hashset to maintain all the integers int nums1, then check if nums2 also have those integers, if yes, add to the result list.

I am not sure if there are more advanced solution out there.


 public int[] intersection(int[] nums1, int[] nums2) {  
     HashSet<Integer> set=new HashSet<Integer>();  
     for(int i=0;i<nums1.length;i++){  
       set.add(nums1[i]);  
     }  
     List<Integer> list=new ArrayList<Integer>();  
     for(int i=0;i<nums2.length;i++){  
       if(set.contains(nums2[i])){  
         list.add(nums2[i]);  
         set.remove(nums2[i]);  
       }  
     }  
     int[] res=new int[list.size()];  
     for(int i=0;i<list.size();i++){  
       res[i]=list.get(i);  
     }  
     return res;  
   }  

No comments:

Post a Comment