作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


  • Difficulty: Easy

题目描述

Given two arrays, write a function to compute their intersection.

Example 1:

Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]

Example 2:

Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [4,9]

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?

解题方法

Java排序+双指针

题目的意思是找出两个数组中相同的元素,这个题目前面题使用HashSet去除的重复元素,这个题里边直接用ArrayList存储相同元素即可。

所以可以参考前面的,创建一个Arraylist,然后对两个数组进行排序,这样才能比较,根据不同的比较结果采取不同的措施。

对了,双指针的方法节省了不少空间。高票答案用的HashMap,效率明显没有双指针高。

public class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
ArrayList<Integer> arraylist = new ArrayList<Integer>();
//一定写上<Integer>,否则没法自动拆包装包
Arrays.sort(nums1);
Arrays.sort(nums2);
int index1 = 0;
int index2 = 0;
while (index1 < nums1.length && index2 < nums2.length) {
if (nums1[index1] == nums2[index2]) {
arraylist.add(nums1[index1]);
index1++;
index2++;
} else if (nums1[index1] < nums2[index2]) {
index1++;
} else {
index2++;
}
}
int answer[] = new int[arraylist.size()];
for (int i = 0; i < arraylist.size(); i++) {
answer[i] = arraylist.get(i);
}
return answer;
}
}

AC: 3 ms 超过96.76%

Python排序+双指针

看到题目说了如果已经排序了会怎么样,这是一个很明显的需要排序的提示,告诉我们先排序。下面的操作就像merge两个有序链表差不多,分别从两个的起始位置判断是否相等即可。

需要注意的是题目要求的是结果中的出现次数等于两个数组交集部分的次数,所以当两个数组元素相等的时候需要把两个指针同时右移。

时间复杂度O(NlogN),空间复杂度O(1).

class Solution:
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
nums1.sort()
nums2.sort()
l1, l2 = 0, 0
N1, N2 = len(nums1), len(nums2)
res = []
while l1 != N1 and l2 != N2:
if nums1[l1] == nums2[l2]:
res.append(nums1[l1])
l1 += 1
l2 += 1
elif nums1[l1] < nums2[l2]:
l1 += 1
else:
l2 += 1
return res

Python解法使用字典

使用字典对两个数组出现的数字进行统计,然后直接判断数字是否在另一个字典里出现过,把结果直接拼接上两个的最小次数个当前数字。

时间复杂度O(N),空间复杂度O(N).打败了98%的提交。

class Solution:
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
count1 = collections.Counter(nums1)
count2 = collections.Counter(nums2)
res = []
for k, v in count1.items():
if k in count2:
res += [k] * min(v, count2[k])
return res

日期

2017 年 1 月 11 日
2018 年 11 月 6 日 —— 腰酸背痛要废了
2018 年 11 月 16 日 —— 又到周五了!

【LeetCode】350. Intersection of Two Arrays II 解题报告(Java & Python)的更多相关文章

  1. 【LeetCode】522. Longest Uncommon Subsequence II 解题报告(Python)

    [LeetCode]522. Longest Uncommon Subsequence II 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemin ...

  2. 26. leetcode 350. Intersection of Two Arrays II

    350. Intersection of Two Arrays II Given two arrays, write a function to compute their intersection. ...

  3. [LeetCode] 350. Intersection of Two Arrays II 两个数组相交II

    Given two arrays, write a function to compute their intersection. Example 1: Input: nums1 = [1,2,2,1 ...

  4. [LeetCode] 350. Intersection of Two Arrays II 两个数组相交之二

    Given two arrays, write a function to compute their intersection. Example 1: Input: nums1 = [1,2,2,1 ...

  5. Python [Leetcode 350]Intersection of Two Arrays II

    题目描述: Given two arrays, write a function to compute their intersection. Example:Given nums1 = [1, 2, ...

  6. LeetCode 350. Intersection of Two Arrays II (两个数组的相交之二)

    Given two arrays, write a function to compute their intersection. Example:Given nums1 = [1, 2, 2, 1] ...

  7. LeetCode 350. Intersection of Two Arrays II

    Given two arrays, write a function to compute their intersection. Example:Given nums1 = [1, 2, 2, 1] ...

  8. 【LeetCode】963. Minimum Area Rectangle II 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 线段长+线段中心+字典 日期 题目地址:https: ...

  9. 【LeetCode】445. Add Two Numbers II 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 先求和再构成列表 使用栈保存节点数字 类似题目 日期 ...

随机推荐

  1. Linux环境下R和R包安装及其管理

    前言 R对windows使用很友好,对Linux来说充满了敌意.小数据可以在windows下交互操作,效果很好很棒.可是当我们要处理大数据,或者要在集群上搭建pipeline时,不得不面对在Linux ...

  2. 64-Unique Binary Search Trees

    96. Unique Binary Search Trees My Submissions Question Editorial Solution Total Accepted: 82788 Tota ...

  3. javaSE中级篇2 — 工具类篇 — 更新完毕

    1.工具类(也叫常用类)-- 指的是别人已经写好了的,我们只需要拿来用就行了 官网网址:Overview (Java Platform SE 8 ) (oracle.com) ---- 但是这个是英文 ...

  4. mysql事务控制语言TCL

    Transaction Control Language 事务控制语言 事务:一个或一组sql语句组成一个执行单元,这个执行单元作为不可分割的整体执行.如果某个语句执行错误,整个单元回滚到最初的状态. ...

  5. 日常Java 2021/11/4

    ServerSocket类的方法服务器应用程序通过使用java.net.ServerSocket类以获取一个端口,并且侦听客户端请求. 构造方法: public ServerSocket(int po ...

  6. day13 grep命令

    day13 grep命令 linux三剑客之grep命令 介绍 grep(global search regular expression(RE) and print out the line,全面搜 ...

  7. 26. Linux GIT

    windows git 下载链接: Msysgit   https://git-scm.com/download/win 1 进入git bash进行第一次配置 git config --global ...

  8. flink---实时项目--day02-----1. 解析参数工具类 2. Flink工具类封装 3. 日志采集架构图 4. 测流输出 5. 将kafka中数据写入HDFS 6 KafkaProducer的使用 7 练习

    1. 解析参数工具类(ParameterTool) 该类提供了从不同数据源读取和解析程序参数的简单实用方法,其解析args时,只能支持单只参数. 用来解析main方法传入参数的工具类 public c ...

  9. 大数据学习day20-----spark03-----RDD编程实战案例(1 计算订单分类成交金额,2 将订单信息关联分类信息,并将这些数据存入Hbase中,3 使用Spark读取日志文件,根据Ip地址,查询地址对应的位置信息

    1 RDD编程实战案例一 数据样例 字段说明: 其中cid中1代表手机,2代表家具,3代表服装 1.1 计算订单分类成交金额 需求:在给定的订单数据,根据订单的分类ID进行聚合,然后管理订单分类名称, ...

  10. 用户名、密码、整数等常用的js正则表达式

    1 用户名正则 //用户名正则,4到16位(字母,数字,下划线,减号) var uPattern = /^[a-zA-Z0-9_-]{4,16}$/; //输出 true console.log(uP ...