【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/ 目录 题目描述 题目大意 解题方法 先求和再构成列表 使用栈保存节点数字 类似题目 日期 ...
随机推荐
- PPT插件——iSlide全功能解析
做幻灯展示是我们日常工作中不可缺少的一部分,有的人喜欢用代码如Latex, markdown+pandoc+revealjs 或 bookdown.这些都是自动化做幻灯的好工具.我也都有过体会,确实简 ...
- windows系统 svn自动更新
如果对svn不熟悉,当svn上面有更新时,想看到实时效果,就得去web目录手动更新,比较麻烦 其它svn有一个自动更新的功能 利用 hook 在svn 仓库目录下面有一个hook目录 在post- ...
- 表格合并单元格【c#】
gridBranchInfo.DataSource = dtBranchViewList; gridBranchInfo.DataBind(); Random random = new Random( ...
- 学习java的第十天
一.今日收获 1.java完全学习手册第二章2.9程序流程控制中的选择结构与顺序结构的例题 2.观看哔哩哔哩上的教学视频 二.今日问题 1.例题的问题不大,需要注意大小写,新的语句记忆不牢 2.哔哩哔 ...
- 初学js正则表达式之密码强度验证
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- CAS你知道吗
1.比较并交换 CASDemo /** * CAS => compareAndSet * 比较并交换 */ public class CASDemo { public static void m ...
- Vue相关,Vue生命周期及对应的行为
先来一张经典图 生命钩子函数 使用vue的朋友们知道,生命周期函数长这样- mounted: function() { } // 或者 mounted() { } 注意点,Vue的所有生命周期函数都是 ...
- vim编码设置(转)
vim里面的编码主要跟三个参数有关:enc(encoding).fenc(fileencoding).fence(fileencodings) fenc是当前文件的编码,也就是说,一个在vim里面已经 ...
- Android Https相关完全解析
转载: 转载请标明出处: http://blog.csdn.net/lmj623565791/article/details/48129405: 本文出自:[张鸿洋的博客] 一.概述 其实这篇文章理论 ...
- 颜色RGB值对照表
转载自 http://www.91dota.com/?p=49# 常用颜色的RGB值及中英文名称 颜 色 RGB值 英文名 中文名 #FFB6C1 LightPink 浅粉红 #F ...