题目来源:https://leetcode.com/problems/intersection-of-two-arrays-ii
题目难度:Easy
题目
Given two arrays, write a function to compute their intersection.
Example 1:
1 | Input: nums1 = [1,2,2,1], nums2 = [2,2] |
Example 2:
1 | Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] |
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?
解答1[Java]
思路
借助一个 Map,先统计数组1中每一个数组的个数,然后再遍历数组2,如果 Map 中存在此元素,则加入到结果数组,并且把 Map 中统计的数量减去 1。
实现
1 | public class Solution { |
复杂度分析
HashMap 的 get()
时间复杂度为 $O(1)$。
解答2[Java]
思路
先对两个数组进行排序,然后两个数组分别设一个指针,判断当前指针指向的元素是否相等,如果相等就把指针当前指向的元素加入结果数组。如果不相等,哪个指向的元素更小,哪个指针向右移动,另外一个指针保持位置不变。
实现
1 | class Solution { |