[LeetCode] Intersection of Two Arrays II
2016-05-21 15:04
399 查看
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 =
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 num2’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?
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 num2’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?
解题思路
两个map分别存储两个数组的元素出现次数,然后以最少出现次数决定是否出现在结果数组中以及出现在结果数组中的次数。实现代码
// Runtime: 13 ms public class Solution { public int[] intersect(int[] nums1, int[] nums2) { Map<Integer, Integer> map1 = new HashMap<Integer, Integer>(); for (int num : nums1) { if (map1.containsKey(num)) { map1.put(num, map1.get(num) + 1); } else { map1.put(num, 1); } } Map<Integer, Integer> map2 = new HashMap<Integer, Integer>(); for (int num : nums2) { if (map2.containsKey(num)) { map2.put(num, map2.get(num) + 1); } else { map2.put(num, 1); } } List<Integer> list = new ArrayList<Integer>(); for (Map.Entry<Integer, Integer> entry : map1.entrySet()) { int times = entry.getValue(); if (map2.containsKey(entry.getKey())) { times = Math.min(times, map2.get(entry.getKey())); } else { times = 0; } for (int i = 0; i < times; i++) { list.add(entry.getKey()); } } int[] res = new int[list.size()]; for (int i = 0; i < list.size(); i++) { res[i] = list.get(i); } return res; } }
相关文章推荐
- 使用终端模拟器通过wifi连接eclipse
- 76-Search in Rotated Sorted Array
- https://segmentfault.com/a/1190000002620961
- C语言到底怎么分配空间
- python3学习记录——安装pyspider中lxml安装问题
- Quartz使用-入门使用
- Android Studio报错:Gradle DSL method not found: 'android()'
- C#—Windows应用基础2
- react native安装笔记
- 计组_补码1位乘
- 工具-VMWARE技巧-桥接连外网-WIN7
- 字符串------打印1到最大的n位数
- 工资税
- iOS - 通过runtime获取某个类中所有的变量和方法
- python实现简单购物商城
- delphi中UTF8Deocde的问题
- 套接字编程--TCP
- 正则表达式整理
- PHP中获取函数调用时实际传递的参数信息
- [Ruby On Rails] Rails 路由学习笔记