博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode刷题350 两个数组的交集II Intersection of Two Arrays II(简单) Python Java
阅读量:4128 次
发布时间:2019-05-25

本文共 2513 字,大约阅读时间需要 8 分钟。

题目大意:

给定两个数组,编写一个函数来计算它们的交集。

示例 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 的元素存储在磁盘上,磁盘内存是有限的,并且你不能一次加载所有的元素到内存中,你该怎么办?

解法一:效率比较低

class Solution(object):    def intersect(self, nums1, nums2):        """        :type nums1: List[int]        :type nums2: List[int]        :rtype: List[int]        """        res = []        for k in nums1:            if k in nums2:                res.append(k)                nums2.remove(k)        return res

解法二:先排序,因为两只数组已经按升序排好序,所以当 i 指针和 j 指针指向的数值相等时,放入新list;如果 i 指针指向的数 < j 指针指向的数,那么 i 指针前进;如果 i 指针指向的数 > j 指针指向的数,那么 j 指针前进; 错位遍历。

class Solution(object):    def intersect(self, nums1, nums2):        """        :type nums1: List[int]        :type nums2: List[int]        :rtype: List[int]        """        ans = []        nums1.sort()        nums2.sort()        i = j = 0        while i

 

以下是Java版本:

这道题是之前那道的拓展,不同之处在于这道题允许我们返回重复的数字,而且是尽可能多的返回,之前那道题是说有重复的数字只返回一个就行。那么这道题我们用哈希表来建立nums1中字符和其出现个数之间的映射, 然后遍历nums2数组,如果当前字符在哈希表中的个数大于0,则将此字符加入结果res中,然后哈希表的对应值自减1

题意: 求两个数组的交集(包括重复出现的元素)。

思路: 1.遍历数组nums1,将其中的元素放入HashMap<Integer,Integer>中进行统计; 

2.新建ArrayList作为存储交集的元素(可重复元素); 
3.遍历数组nums2,如果元素num2map中出现过,则将其加入到list中,并将其对应的值-1; 
4.
list转为数组返回即可。

public class Solution {    public int[] intersect(int[] nums1, int[] nums2) {        Map
map = new HashMap
(); for(int num1:nums1){ if(!map.containsKey(num1)){ map.put(num1,1); }else{ map.put(num1,map.get(num1) + 1); } } List
list = new ArrayList
(); for(int num2:nums2){ if(map.containsKey(num2) && map.get(num2) > 0){ list.add(num2); map.put(num2,map.get(num2) - 1); } } int[] res = new int[list.size()]; for(int i = 0;i < list.size();i++){ res[i] = list.get(i); } return res; }}

思路:

承接上题

不同的是,这里可以有重复元素。因此使用List即可。

1.	public class Solution {  2.	    public int[] intersect(int[] nums1, int[] nums2) {          3.	          4.	        List
list = new ArrayList
(); 5. List
interList = new ArrayList
(); 6. 7. for(int num:nums1) { 8. list.add(num); 9. } 10. 11. for(int i=0;i

 

转载地址:http://kvuvi.baihongyu.com/

你可能感兴趣的文章
C#中ColorDialog需点两次确定才会退出的问题
查看>>
数据库
查看>>
nginx反代 499 502 bad gateway 和timeout
查看>>
linux虚拟机安装tar.gz版jdk步骤详解
查看>>
python实现100以内自然数之和,偶数之和
查看>>
python数字逆序输出及多个print输出在同一行
查看>>
苏宁产品经理面经
查看>>
百度产品经理群面
查看>>
去哪儿一面+平安科技二面+hr面+贝贝一面+二面产品面经
查看>>
element ui 弹窗在IE11中关闭时闪现问题修复
查看>>
vue 遍历对象并动态绑定在下拉列表中
查看>>
Vue动态生成el-checkbox点击无法选中的解决方法
查看>>
python __future__
查看>>
MySQL Tricks1
查看>>
python 变量作用域问题(经典坑)
查看>>
pytorch
查看>>
pytorch(三)
查看>>
ubuntu相关
查看>>
C++ 调用json
查看>>
nano中设置脚本开机自启动
查看>>