题目:
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?
链接:
https://leetcode.com/problems/intersection-of-two-arrays-ii/#/description
3/12/2017
1 public class Solution { 2 public int[] intersect(int[] nums1, int[] nums2) { 3 HashMap<Integer, Integer> h1 = new HashMap<Integer, Integer>(); 4 ArrayList<Integer> a = new ArrayList<Integer>(); 5 6 for (int i = 0; i < nums1.length; i++) { 7 if (h1.containsKey(nums1[i])) { 8 h1.put(nums1[i], h1.get(nums1[i]) + 1); 9 } else { 10 h1.put(nums1[i], 1); 11 } 12 } 13 for (int i = 0; i < nums2.length; i++) { 14 if (h1.containsKey(nums2[i])) { 15 if (h1.get(nums2[i]) > 0) { 16 a.add(nums2[i]); 17 h1.put(nums2[i], h1.get(nums2[i]) - 1); 18 } else { 19 h1.remove(nums2[i]); 20 } 21 } 22 } 23 int ret[] = new int[a.size()]; 24 int index = 0; 25 for (Integer i: a) { 26 ret[index++] = i; 27 } 28 return ret; 29 } 30 }
followup:
1. 如果输入是sort的,可以用2个指针完成
2. 如果nums1的值的个数远小于nums2,还是hashmap方法好吧?
3. 可以取决于nums1的大小,如果nums1小的话可以用它存入hash;否则external sort2个数组,再来比较
看讨论别人用Python写的非常简洁,用的是collections.Counter。虽然平时用collections比较多,不过这个却从来没有用过。另外除非面试官很了解Python,否则还是解释起来比较麻烦。面试时候尝试用Java会比较好些。