程序媛詹妮弗
终身学习

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

Example 1:

Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2]

Example 2:

Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [9,4]

 

题意:

如题

 

Solution1:  HashSet

1.  Scan nums1,  put items in nums1 to set1

2. Scan nums2, check each item is contained in set1 

     

   

 

注意: HashSet.contains() -> O(1) 

 

code

 1 class Solution {
 2   public int[] intersection(int[] nums1, int[] nums2) {
 3         HashSet <Integer> set1 = new HashSet<>(); 
 4         HashSet <Integer> resSet = new HashSet<>(); 
 5         
 6         for (int i = 0; i < nums1.length; i ++) {
 7             set1.add(nums1[i]);
 8         }
 9         for (int i = 0; i < nums2.length; i ++) {
10             if (set1.contains(nums2[i])) {  
11                 resSet.add(nums2[i]);
12             }
13         } 
14         //  resSet -> int[]res
15         int [] res = new int[resSet.size()];
16         int index = 0;
17         for (int num : resSet) {
18             res[index++] = num;
19         }
20         return res;
21     }
22 }

 

posted on 2018-10-18 14:45  程序媛詹妮弗  阅读(177)  评论(0编辑  收藏  举报