首页 > 代码库 > Intersection of Two Arrays

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].

利用较小的数组建set 节省空间

 1 public class Solution {
 2     /**
 3      * @param nums1 an integer array
 4      * @param nums2 an integer array
 5      * @return an integer array
 6      */
 7     public int[] intersection(int[] nums1, int[] nums2) {
 8         // Write your code here
 9         if(nums1==null||nums2==null) return null;
10         if(nums1.length==0||nums2.length==0) return new int[0];
11         
12         Set<Integer> set = new HashSet<Integer>();
13         List<Integer> res = new ArrayList<Integer>();
14         
15         int[] num1 = nums1.length>nums2.length?nums2: nums1;
16         int[] num2 = nums1.length<nums2.length?nums2: nums1;
17         
18         for(int i: num1){
19             set.add(i);
20         }
21         
22         for(int i: num2){
23             if(set.contains(i)){
24                 res.add(i);
25                 set.remove(i);
26             }
27             if(set.size()==0) break;
28         }
29         int[] resInt = new int[res.size()];
30         int index =0;
31         for(Integer i : res){
32             resInt[index++]=i;
33         }
34         return resInt;
35     }
36 }

 

Intersection of Two Arrays