【LeetCode题解】349_两个数组的交集
【LeetCode题解】349_两个数组的交集
描述
给定两个数组,编写一个函数来计算它们的交集。
示例1:
输入:nums1 = [1,2,2,1], nums2 = [2,2]
输出:[2]
示例2:
输入:nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出:[9,4]
说明:
- 输出结果中的每个元素一定是唯一的。
- 我们可以不考虑输出结果的顺序。
方法一:两个哈希表
Java 实现
import java.util.Set;
import java.util.HashSet;
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> set1 = new HashSet<>();
Set<Integer> set2 = new HashSet<>();
for (int num : nums1) {
set1.add(num);
}
for (int num : nums2) {
if (set1.contains(num)) {
set2.add(num);
}
}
int[] ret = new int[set2.size()];
int i = 0;
for (int num : set2) {
ret[i++] = num;
}
return ret;
}
}
// Runtime: 2 ms
// Your runtime beats 98.84 % of java submissions.
复杂度分析:
- 时间复杂度:\(O(n)\)
- 空间复杂度:\(O(n)\)
类似的 Java 实现
import java.util.List;
import java.util.ArrayList;
import java.util.Set;
import java.util.HashSet;
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> set = new HashSet<>();
for (int num : nums1) {
set.add(num);
}
List<Integer> list = new ArrayList<>();
for (int num : nums2) {
if (set.contains(num)) {
list.add(num);
set.remove(num);
}
}
int[] ret = new int[list.size()];
for (int i = 0; i < list.size(); ++i) {
ret[i] = list.get(i);
}
return ret;
}
}
Python 实现
class Solution:
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
return list(set(nums1) & set(nums2))
复杂度分析同上。
类似的 Python 实现
class Solution:
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
if len(nums1) == 0 or len(nums2) == 0:
return []
ret = []
s1 = set(nums1)
s2 = set(nums2)
for num in s1:
if num in s2:
ret.append(num)
return ret
# Runtime: 36 ms
# Your runtime beats 100.00 % of python3 submissions.
复杂度分析同上。
方法二:双指针
Java 实现
import java.util.Arrays;
import java.util.Set;
import java.util.HashSet;
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Arrays.sort(nums1);
Arrays.sort(nums2);
Set<Integer> set = new HashSet<>();
int i = 0, j= 0;
while (i < nums1.length && j < nums2.length) {
if (nums1[i] < nums2[j]) {
++i;
} else if (nums1[i] > nums2[j]) {
++j;
} else {
set.add(nums1[i]);
++i;
++j;
}
}
int[] ret = new int[set.size()];
int k = 0;
for (int num : set) {
ret[k++] = num;
}
return ret;
}
}
// Runtime: 3 ms
// Your runtime beats 90.80 % of java submissions.
复杂度分析:
- 时间复杂度:\(O(nlog(n))\)
- 空间复杂度:\(O(n)\)
方法三:二分查找
Java 实现
import java.util.Arrays;
import java.util.Set;
import java.util.HashSet;
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Arrays.sort(nums2);
Set<Integer> set = new HashSet<>();
for (int num : nums1) {
if (binarySearch(nums2, num)) {
set.add(num);
}
}
int[] ret = new int[set.size()];
int i = 0;
for (int num : set) {
ret[i++] = num;
}
return ret;
}
private boolean binarySearch(int[] nums, int target) {
int low = 0;
int high = nums.length - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (nums[mid] == target) {
return true;
} else if (nums[mid] < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return false;
}
}
// Runtime: 6 ms
// Your runtime beats 23.44 % of java submissions.
复杂度分析:
- 时间复杂度:\(O(nlog(n))\)
- 空间复杂度:\(O(n)\)
方法四
Java 实现
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
// 确定数组 nums1 的取值范围
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
for (int num : nums1) {
if (num > max) {
max = num;
}
if (num < min) {
min = num;
}
}
boolean[] arr = new boolean[max - min + 1];
for (int num : nums1) {
arr[num - min] = true;
}
// 判断数组 nums2 中的数是否在数组 nums1 中存在,
// 如果存在保存在数组 tmp 中
int[] tmp = new int[max - min + 1];
int idx = 0;
for (int num : nums2) {
if (num >= min && num <= max && arr[num - min]) {
tmp[idx++] = num;
arr[num- min] = false;
}
}
// 返回结果
int[] ret = new int[idx];
for (int i = 0; i < idx; i++) {
ret[i] = tmp[i];
}
return ret;
}
}
// Runtime: 0 ms
// Your runtime beats 100.00 % of java submissions.
复杂度分析:
- 时间复杂度:\(O(n)\)
- 空间复杂度:\(O(n)\)
【LeetCode题解】349_两个数组的交集的更多相关文章
- leetcode 349:两个数组的交集I
Problem: Given two arrays, write a function to compute their intersection. 中文:已知两个数组,写一个函数来计算它们的交集 E ...
- leetcode NO.349 两个数组的交集 (python实现)
来源 https://leetcode-cn.com/problems/intersection-of-two-arrays/ 题目描述 给定两个数组,写一个函数来计算它们的交集. 例子: 给定 nu ...
- 【LeetCode题解】350_两个数组的交集Ⅱ
目录 [LeetCode题解]350_两个数组的交集Ⅱ 描述 方法一:映射 Java 实现 Python 实现 类似的 Python 实现 方法二:双指针 Java 实现 Python 实现 [Lee ...
- 【Leetcode】【简单】【350. 两个数组的交集 II】【JavaScript】
题目描述 350. 两个数组的交集 II 给定两个数组,编写一个函数来计算它们的交集. 示例 1: 输入: nums1 = [1,2,2,1], nums2 = [2,2]输出: [2,2] 示例 2 ...
- 前端与算法 leetcode 350. 两个数组的交集 II
目录 # 前端与算法 leetcode 350. 两个数组的交集 II 题目描述 概要 提示 解析 解法一:哈希表 解法二:双指针 解法三:暴力法 算法 # 前端与算法 leetcode 350. 两 ...
- Java实现 LeetCode 350 两个数组的交集 II(二)
350. 两个数组的交集 II 给定两个数组,编写一个函数来计算它们的交集. 示例 1: 输入: nums1 = [1,2,2,1], nums2 = [2,2] 输出: [2,2] 示例 2: 输入 ...
- Java实现 LeetCode 349 两个数组的交集
349. 两个数组的交集 给定两个数组,编写一个函数来计算它们的交集. 示例 1: 输入: nums1 = [1,2,2,1], nums2 = [2,2] 输出: [2] 示例 2: 输入: num ...
- LeetCode初级算法之数组:350 两个数组的交集 II
两个数组的交集 II 题目地址:https://leetcode-cn.com/problems/intersection-of-two-arrays-ii/ 给定两个数组,编写一个函数来计算它们的交 ...
- Leecode刷题之旅-C语言/python-349两个数组的交集
/* * @lc app=leetcode.cn id=349 lang=c * * [349] 两个数组的交集 * * https://leetcode-cn.com/problems/inters ...
随机推荐
- 使用oracle9的 odbc 连接oracle11
客户机上基于Oracle 9i的ODBC数据源,无法连接oracle 11G数据库,提示错误为:error ORA-01017, Invalid Username / Password.奇怪的是:sq ...
- PostgreSQL递归查询
原料 --创建组织架构表 create table "Org"( "OrgId" ) primary key, "ParentId" ), ...
- .NET中异常与错误码优劣势对比
.NET之所以选择异常,而不是返回错误码来报告异常,是由于前者有以下几个优势: 1.异常与oop语言的结合性更好.oop语言经常需要对成员签名强加限制,比如c#中的构造函数.操作符重载和属性,开发者对 ...
- AJPFX平台介绍
AJPFX设立于英国,业务框架扩展到欧洲.美洲和亚洲,在新加坡设有专门的亚洲地区服务部门.AJPFX旨在以极具竞争力的交易成本,也就是银行间市场核心点差和低水平的手续费,使客户在交易中获取最大的利润空 ...
- Posix消息队列注意事项
随内核的持续性 读总是返回最高优先级的最早消息. 当往一个空队列放置一个消息时,允许产生一个信号或启动一个线程. 可认为是一个消息链表 队列中每个消息具有 1.一个无符号整数优先级 2.消息的数据部分 ...
- Nova 通过Python API 查询,创建,删除flavor
[root@controller ~]# cat flavor.py from novaclient import client as nvclient from novaclient import ...
- D - How Many Tables (并查集)(水题)
点击打开链接 Today is Ignatius' birthday. He invites a lot of friends. Now it's dinner time. Ignatius want ...
- docker启动时报错
docker安装成功后,启动时报错. 1.后来排查后发现yum install docker安装的是从test存储库中安装的. 后来我指定了特定的版本后,而且从stable存储库安装的,以后再启动就好 ...
- 反弹Shell小结
1.NC反弹shell 1.1.正向反弹shell 服务器 nc -lvvp 7777 -e /bin/bash 攻击机 nc server-ip 7777 1.2.反向反弹shell 攻击机 nc ...
- ElasticSearch5.0——IK词库加载
Dictionary ConfigurationIKAnalyzer.cfg.xml can be located at {conf}/analysis-ik/config/IKAnalyzer.cf ...