算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !
今天和大家聊的问题叫做 两个数组的交集 II,我们先来看题面:
https://leetcode-cn.com/problems/interp-of-two-arrays-ii/
Given two integer arrays nums1 and nums2, return an array of their interp. Each element in the result must appear as many times as it shows in both arrays and you may return the result in any order.
给定两个数组,编写一个函数来计算它们的交集。
示例
示例 1:
输入:nums1 = [1,2,2,1], nums2 = [2,2]
输出:[2,2]
示例 2:
输入:nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出:[4,9]
说明:
输出结果中每个元素出现的次数,应与元素在两个数组中出现次数的最小值一致。
我们可以不考虑输出结果的顺序。
进阶:
如果给定的数组已经排好序呢?你将如何优化你的算法?
如果 nums1 的大小比 nums2 小很多,哪种方法更优?
如果 nums2 的元素存储在磁盘上,内存是有限的,并且你不能一次加载所有的元素到内存中,你该怎么办?
解题
用Map来建立nums1中字符和其出现个数之间的映射, 然后遍历nums2数组,如果当前字符在Map中的个数大于0,则将此字符加入结果res中,然后Map的对应值自减1。
class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
List<Integer> tmp = new ArrayList<>();
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < nums1.length; i++) {
Integer value = map.get(nums1[i]);
map.put(nums1[i], (value == null ? 0 : value) + 1);
}
for (int i = 0; i < nums2.length; i++) {
if (map.containsKey(nums2[i]) && map.get(nums2[i]) != 0) {
tmp.add(nums2[i]);
map.put(nums2[i], map.get(nums2[i]) - 1);
}
}
int[] result = new int[tmp.size()];
int i = 0;
for (Integer e : tmp)
result[i++] = e;
return result;
}
}
好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。
上期推文: