350. Intersection of Two Arrays II java solutions

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

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

Note:

  • Each element in the result should appear as many times as it shows in both arrays.
  • The result can be in any order.

 

Follow up:

  • What if the given array is already sorted? How would you optimize your algorithm?
  • What if nums1's size is small compared to nums2's size? Which algorithm is better?
  • What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?

Subscribe to see which companies asked this question

 1 public class Solution {
 2     public int[] intersect(int[] nums1, int[] nums2) {
 3         Set<Integer> set = new HashSet<Integer>();
 4         Arrays.sort(nums1);
 5         Arrays.sort(nums2);
 6         for(int i = 0,j = 0; i < nums1.length && j < nums2.length;){
 7             if(nums1[i] == nums2[j]){
 8                 set.add(i++);
 9                 j++;
10             }else if(nums1[i] < nums2[j]) i++;
11             else j++;
12         }
13         
14         int[] ans = new int[set.size()];
15         int k = 0;
16         for(Integer n : set){
17             ans[k++] = nums1[n];
18         }
19         return ans;
20     }
21 }

使用hashset 记录重复出现元素的下标。

posted @ 2016-07-08 16:43  Miller1991  阅读(272)  评论(0编辑  收藏  举报