【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_两个数组的交集的更多相关文章

  1. leetcode 349:两个数组的交集I

    Problem: Given two arrays, write a function to compute their intersection. 中文:已知两个数组,写一个函数来计算它们的交集 E ...

  2. leetcode NO.349 两个数组的交集 (python实现)

    来源 https://leetcode-cn.com/problems/intersection-of-two-arrays/ 题目描述 给定两个数组,写一个函数来计算它们的交集. 例子: 给定 nu ...

  3. 【LeetCode题解】350_两个数组的交集Ⅱ

    目录 [LeetCode题解]350_两个数组的交集Ⅱ 描述 方法一:映射 Java 实现 Python 实现 类似的 Python 实现 方法二:双指针 Java 实现 Python 实现 [Lee ...

  4. 【Leetcode】【简单】【350. 两个数组的交集 II】【JavaScript】

    题目描述 350. 两个数组的交集 II 给定两个数组,编写一个函数来计算它们的交集. 示例 1: 输入: nums1 = [1,2,2,1], nums2 = [2,2]输出: [2,2] 示例 2 ...

  5. 前端与算法 leetcode 350. 两个数组的交集 II

    目录 # 前端与算法 leetcode 350. 两个数组的交集 II 题目描述 概要 提示 解析 解法一:哈希表 解法二:双指针 解法三:暴力法 算法 # 前端与算法 leetcode 350. 两 ...

  6. Java实现 LeetCode 350 两个数组的交集 II(二)

    350. 两个数组的交集 II 给定两个数组,编写一个函数来计算它们的交集. 示例 1: 输入: nums1 = [1,2,2,1], nums2 = [2,2] 输出: [2,2] 示例 2: 输入 ...

  7. Java实现 LeetCode 349 两个数组的交集

    349. 两个数组的交集 给定两个数组,编写一个函数来计算它们的交集. 示例 1: 输入: nums1 = [1,2,2,1], nums2 = [2,2] 输出: [2] 示例 2: 输入: num ...

  8. LeetCode初级算法之数组:350 两个数组的交集 II

    两个数组的交集 II 题目地址:https://leetcode-cn.com/problems/intersection-of-two-arrays-ii/ 给定两个数组,编写一个函数来计算它们的交 ...

  9. Leecode刷题之旅-C语言/python-349两个数组的交集

    /* * @lc app=leetcode.cn id=349 lang=c * * [349] 两个数组的交集 * * https://leetcode-cn.com/problems/inters ...

随机推荐

  1. 【转】不用软件,解压Win8/Win8.1的install.wim文件

    今天用好压解压Windows 8.1的install.wim文件,居然提示文件损坏,换了7Z仍然如此:其实文件是好的.只不过这些软件暂时不支持罢了,还好可以用dism命令来手动完成. 一.检查镜像版本 ...

  2. EAS 最大单据号获取

    BaseService using System; using System.Collections.Generic; using System.Linq; using System.Text; us ...

  3. [react002] component基本用法

    1 什么是component 设计接口的时候,把通用的设计元素(按钮,表单框,布局组件等)拆成接口良好定义的可复用的组件. 这样,下次开发相同界面程序时就可以写更少的代码,也意义着更高的开发效率,更少 ...

  4. Java异常:选择Checked Exception还是Unchecked Exception?

    http://blog.csdn.net/kingzone_2008/article/details/8535287 Java包含两种异常:checked异常和unchecked异常.C#只有unch ...

  5. SQL集合运算

    注:UserInfo一共29条记录 select * from UserInfo union --并集(29条记录)(相同的只出现一次) select * from UserInfo select * ...

  6. .net使用QQ邮箱发送邮件

    /// <summary> /// 发送邮件 /// </summary> /// <param name="mailTo">要发送的邮箱< ...

  7. 数据与任务的并行---Parallel类

    Parallel类是对线程的抽象,提供数据与任务的并行性.类定义了静态方法For和ForEach,使用多个任务来完成多个作业.Parallel.For和Parallel.ForEach方法在每次迭代的 ...

  8. WP8.1StoreApp(WP8.1RT)---添加推送功能和获取系统信息

    添加推送通知 1:Package.appxmanifest中的声明添加后台任务的推送通知权限 2:var channel = await PushNotificationChannelManager. ...

  9. python--面向对象(02)

    1.类的成员 在类中你能写的所有内容都是类的成员 class 类名: # 方法 def __init__(self, 参数1, 参数2....): # 属性变量量 self.属性1 = 参数1 sel ...

  10. 如何学习sql语言?

    如何学习 SQL 语言? https://www.zhihu.com/question/19552975 没有任何基础的人怎么学SQL? https://www.zhihu.com/question/ ...