【LeetCode】350. Intersection of Two Arrays II 解题报告(Java & Python)
作者: 负雪明烛
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)的更多相关文章
- 【LeetCode】522. Longest Uncommon Subsequence II 解题报告(Python)
[LeetCode]522. Longest Uncommon Subsequence II 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemin ...
- 26. leetcode 350. Intersection of Two Arrays II
350. Intersection of Two Arrays II Given two arrays, write a function to compute their intersection. ...
- [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 ...
- [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 ...
- Python [Leetcode 350]Intersection of Two Arrays II
题目描述: Given two arrays, write a function to compute their intersection. Example:Given nums1 = [1, 2, ...
- LeetCode 350. Intersection of Two Arrays II (两个数组的相交之二)
Given two arrays, write a function to compute their intersection. Example:Given nums1 = [1, 2, 2, 1] ...
- LeetCode 350. Intersection of Two Arrays II
Given two arrays, write a function to compute their intersection. Example:Given nums1 = [1, 2, 2, 1] ...
- 【LeetCode】963. Minimum Area Rectangle II 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 线段长+线段中心+字典 日期 题目地址:https: ...
- 【LeetCode】445. Add Two Numbers II 解题报告(Python & C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 先求和再构成列表 使用栈保存节点数字 类似题目 日期 ...
随机推荐
- Rust 指定安装目录
集群home目录被管理员限制了存储空间,rust安装要100多M,默认安装home目录下,查了一圈,没找到rust指定安装目录的办法. 这里记录下解决办法: 在想要安装的目录执行 mkdir -p c ...
- zabbix 内网机器通信状态
a=0 for xgip in ${xgipset[*]} do let a+=1 fping $xgip|grep alive >/dev/null if [ $a != 3 ];then i ...
- Linux-centos7设置静态IP地址
参考:https://blog.csdn.net/sjhuangx/article/details/79618865
- (转载) Java多线程技术
多线程编程一直是学员们比较头痛和心虚的地方,因为线程执行顺序的不可预知性和调试时候的困难,让不少人在面对多线程的情况下选择了逃避,采用单线程的方式,其实只要我们对线程有了明确的认识,再加上java内置 ...
- 以VuePress的v1.x为基础开发-用户手册
首先配置.vuepress中的config.js module.exports = { title:"用户手册", description: '用户手册', evergreen: ...
- Linux 内存泄漏 valgrind
Valgrind 是个开源的工具,功能很多.例如检查内存泄漏工具---memcheck. Valgrind 安装: 去官网下载: http://valgrind.org/downloads/curre ...
- 商业爬虫学习笔记day3
一. 付费代理发送请求的两种方式 第一种方式: (1)代理ip,形式如下: money_proxy = {"http":"username:pwd@192.168.12. ...
- c#中实现串口通信的几种方法
c#中实现串口通信的几种方法 通常,在C#中实现串口通信,我们有四种方法: 第一:通过MSCOMM控件这是最简单的,最方便的方法.可功能上很难做到控制自如,同时这个控件并不是系统本身所带,所以还得注册 ...
- 容器之分类与各种测试(四)——map
map和set的区别在于,前者key和value是分开的,前者的key不会重复,value可以重复:后者的key即为value,后者的value不允许重复.还有,map在插入时可以使用 [ ]进行(看 ...
- LINUX 系统性能检测工具vmstat
vmstat 有2个参数,第一个是采样时间间隔(单位是s),第二个参数是采样个数. #表示 2s采样一次,一共采样2次 vmstat 2 2 也可以只写第一个参数,让系统一直采样直到停止(ctrl + ...