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

Example 1:

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

Example 2:

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

Note:

  • Each element in the result must be unique.
  • The result can be in any order.

解法:由于结果中要求元素是唯一的,所以用set来统计num1 中的数字。再循环num2中的数字,在set中存在就记录到结果中,同时从set中删除。

Java: HashSet, T: O(n)

class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
HashSet<Integer> set = new HashSet<Integer>();
ArrayList<Integer> res = new ArrayList<Integer>();
//Add all elements to set from array 1
for(int i =0; i< nums1.length; i++) set.add(nums1[i]);
for(int j = 0; j < nums2.length; j++) {
// If present in array 2 then add to res and remove from set
if(set.contains(nums2[j])) {
res.add(nums2[j]);
set.remove(nums2[j]);
}
}
// Convert ArrayList to array
int[] arr = new int[res.size()];
for (int i= 0; i < res.size(); i++) arr[i] = res.get(i);
return arr;
}
}  

Java: Hashset T: O(n)

public class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> set = new HashSet<>();
Set<Integer> intersect = new HashSet<>();
for (int i = 0; i < nums1.length; i++) {
set.add(nums1[i]);
}
for (int i = 0; i < nums2.length; i++) {
if (set.contains(nums2[i])) {
intersect.add(nums2[i]);
}
}
int[] result = new int[intersect.size()];
int i = 0;
for (Integer num : intersect) {
result[i++] = num;
}
return result;
}
}

Java: two points, T: O(nlogn)

public class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> set = new HashSet<>();
Arrays.sort(nums1);
Arrays.sort(nums2);
int i = 0;
int 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[] result = new int[set.size()];
int k = 0;
for (Integer num : set) {
result[k++] = num;
}
return result;
}
}

Java: Binary Search, T: O(nlogn)  

public class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> set = new HashSet<>();
Arrays.sort(nums2);
for (Integer num : nums1) {
if (binarySearch(nums2, num)) {
set.add(num);
}
}
int i = 0;
int[] result = new int[set.size()];
for (Integer num : set) {
result[i++] = num;
}
return result;
} public 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;
}
if (nums[mid] > target) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return false;
}
} 

Python:

class Solution(object):
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
res = []
s = set()
for num in nums1:
s.add(num) for num in nums2:
if num in s:
res.append(num)
s.remove(num) return res

Python:

class Solution(object):
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
nums1=set(nums1)
nums2=set(nums2)
return list(nums1&nums2) 

C++:

class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
set<int> s(nums1.begin(), nums1.end()), res;
for (auto a : nums2) {
if (s.count(a)) res.insert(a);
}
return vector<int>(res.begin(), res.end());
}
};

C++:

class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
vector<int> res;
int i = 0, j = 0;
sort(nums1.begin(), nums1.end());
sort(nums2.begin(), nums2.end());
while (i < nums1.size() && j < nums2.size()) {
if (nums1[i] < nums2[j]) ++i;
else if (nums1[i] > nums2[j]) ++j;
else {
if (res.empty() || res.back() != nums1[i]) {
res.push_back(nums1[i]);
}
++i; ++j;
}
}
return res;
}
};

  

类似题目:

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

[LeetCode] 160. Intersection of Two Linked Lists 求两个链表的交集

  

All LeetCode Questions List 题目汇总

[LeetCode] 349. Intersection of Two Arrays 两个数组相交的更多相关文章

  1. [LeetCode] Intersection of Two Arrays 两个数组相交

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

  2. 349 Intersection of Two Arrays 两个数组的交集

    给定两个数组,写一个函数来计算它们的交集.例子: 给定 num1= [1, 2, 2, 1], nums2 = [2, 2], 返回 [2].提示:    每个在结果中的元素必定是唯一的.    我们 ...

  3. [LintCode] Intersection of Two Arrays 两个数组相交

    Given two arrays, write a function to compute their intersection.Notice Each element in the result m ...

  4. [LeetCode] 349 Intersection of Two Arrays && 350 Intersection of Two Arrays II

    这两道题都是求两个数组之间的重复元素,因此把它们放在一起. 原题地址: 349 Intersection of Two Arrays :https://leetcode.com/problems/in ...

  5. LeetCode 349. Intersection of Two Arrays

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

  6. LeetCode 349 Intersection of Two Arrays 解题报告

    题目要求 Given two arrays, write a function to compute their intersection. 题目分析及思路 给定两个数组,要求得到它们之中共同拥有的元 ...

  7. LeetCode 349. Intersection of Two Arrays (两个数组的相交)

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

  8. 15. leetcode 349. Intersection of Two Arrays

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

  9. [leetcode]349. Intersection of Two Arrays数组交集

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

随机推荐

  1. 前端安全问题之CSRF和XSS

    一.CSRF 1.什么是 CSRF CSRF(全称 Cross-site request forgery),即跨站请求伪造 2.攻击原理 用户登录A网站,并生成 Cookie,在不登出的情况下访问危险 ...

  2. pytho模块的加载顺序

    当前目录如果有同名的系统模块,那么当前目录的模块会被import,系统模块会被忽略,如: 1 ghostwu@ghostwu:~/python/module$ ls 2 import_test.py ...

  3. VS2012 VS2010 VTK引入设置

    1.C/C++ ---> 附加包含的目录 F:/VTK61/VTK-6.1.0/SLN/Filters/Sources F:/VTK61/VTK-6.1.0/VTK-6.1.0/Filters/ ...

  4. Ubuntu 14.04.2配置rsync

    ubuntu系统自带rsync,首先配置/etc/default/rsync,启用daemon模式 修改/etc/rsyncd.conf配置文件 cat /etc/rsyncd.conf # samp ...

  5. Dynamics 365 On-premises和Online 的不同

    1.新建账号的不同:on-premises(下文简称op)是和ad绑定的,所以必须先在ad中新建账号后才能在CRM中新建.而online是和Office365(下文简称O365)绑定的,所以需在O36 ...

  6. HBase数据结构

    1 RowKey 与nosql数据库们一样,RowKey是用来检索记录的主键.访问HBASE table中的行,只有三种方式: 1.通过单个RowKey访问 2.通过RowKey的range(正则) ...

  7. 性能:Output层面

    将数据保存到MySQL中 import java.sql.DriverManager import org.apache.spark.storage.StorageLevel import org.a ...

  8. MyBatis框架的insert节点-向数据库中插入数据

    需求:使用mybatis框架中的insert元素节点向数据库中插入数据 UserMapper.xml UserMapper.java 编写测试方法: @Test public void testAdd ...

  9. Java方法覆盖重写

    方法覆盖重写注意事项: 1.必须保证方法名相同,返回值也相同    @Override:写在方法前面,用来检测方法的覆盖重写是否有效,这个注解不是必要的,就算不写,方法覆盖重写符合要求也是正确的 2. ...

  10. 阿里巴巴编程规约--digest

    所谓卫语句,如果某个条件极其罕见,就应该单独检查该条件,并在该条件为真时立刻从函数中返回.这样的单独检查常常被称为“卫语句”. 微服务之间将DTO,Req放到一个单独的项目中,相关的项目都依赖这个底层 ...