349. Intersection of Two Arrays
来源:互联网 发布:linux oracle清空日志 编辑:程序博客网 时间:2024/06/06 13:19
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1]
, nums2 = [2, 2]
, return [2]
.
Note:
- Each element in the result must be unique.
- The result can be in any order.
class Solution(object): def intersection(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ small = [] big = [] if len(nums1) < len(nums2): small = nums1 big = nums2 else: small = nums2 big = nums1 r = [] for i in small: if i in big and i not in r: r.append(i) return r
虽然AC了,但是用时太长了,需要优化一下
优化的思路是使用set,去重
class Solution(object): def intersection(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ s = set(nums2)# 去重 b = set(nums1) r = [] for i in s: if i in b and i not in r: r.append(i) b.remove(i) return r
0 0
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays[][
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- Homestead 2.0.0 安装指南(2017-04更新)
- UITableView隐藏header
- ZOJ3770-Ranking System
- redis配置参数详解 (转)
- POJ 2282 The Counting Problem
- 349. Intersection of Two Arrays
- java源码解读之TreeMap------jdk 1.7
- Java Web中如何设置多个Access-Control-Allow-Origin
- Go语言的反射三定律
- NSFileManager文件操作的十个小功能
- linux网络编程(6)——TCP网络编程基础
- SuperMapiServer7C MongoDB 版分布式切图缓存迁移
- C程序的编译链接过程
- 辉为科技 ARM主板如何设计外部看门狗电路