快速搭建网站前端插件,建设网官网首页,江苏中益建设官方网站,长沙网站建设去哪好【力扣题】题目描述#xff1a; 【Python3】代码#xff1a;
1、解题思路#xff1a;集合的交集。两个数组都转为集合#xff0c;获取集合的交集。
知识点#xff1a;set(...)#xff1a;转为集合#xff0c;集合的元素不重复。 集合1.intersection(集合2)#xff1a…【力扣题】题目描述 【Python3】代码
1、解题思路集合的交集。两个数组都转为集合获取集合的交集。
知识点set(...)转为集合集合的元素不重复。 集合1.intersection(集合2)获取两个集合都有的元素即两集合的交集。也可以集合1 集合2。 list(...)转为列表。
class Solution:def intersection(self, nums1: List[int], nums2: List[int]) - List[int]:res set(nums1) set(nums2)return list(res)# 或者res set(nums1).intersection(set(nums2))return list(res) 2、解题思路遍历数组依次判断元素是否在另一个数组中用新列表记录两个数组都有的元素。
知识点集合推导式用简洁的方法创建集合集合中的元素不能重复。{ 对元素的简单操作 for 变量 in 可迭代对象 if 条件 }。 列表推导式用简洁的方法创建列表列表中的元素可以重复。[ 对元素的简单操作 for 变量 in 可迭代对象 if 条件 ]。
class Solution:def intersection(self, nums1: List[int], nums2: List[int]) - List[int]:aset set(nums1)res {x for x in nums2 if x in aset}return list(res)# 或者aset, bset set(nums1), set(nums2)return [x for x in bset if x in aset]
也可遍历长度短的数组以提升一点速度。
class Solution:def intersection(self, nums1: List[int], nums2: List[int]) - List[int]:aset set(nums1)bset set(nums2)return self.set_intersection(aset,bset)def set_intersection(self,set1,set2):if len(set1) len(set2):return self.set_intersection(set2,set1)return [x for x in set1 if x in set2]
注解集合推导式、列表推导式
# 集合推导式
res {x for x in nums2 if x in aset}
# 相当于
res set()
for x in nums2:if x in aset:res.append(x)
print(res)# 列表推导式
res [x for x in bset if x in aset]
# 相当于
res []
for x in bset:if x in aset:res.append(x)
print(res) 3、解题思路排序双指针。将两数组都排序依次比较两数组中的元素大小。若相同则用新列表记录若不同则较小数字的指针往后移继续比较直到两数组所有元素比较结束。
知识点列表.sort()在原列表基础上将元素按从小到大排序。 len(列表)获取列表长度即列表中有多少元素。 列表.append(...)往列表尾部添加元素。
class Solution:def intersection(self, nums1: List[int], nums2: List[int]) - List[int]:res []nums1.sort()nums2.sort()len_1, len_2 len(nums1), len(nums2)index_1, index_2 0, 0while index_1 len_1 and index_2 len_2 :val_1 nums1[index_1]val_2 nums2[index_2]if val_1 val_2 and val_1 not in res:res.append(val_1)index_1 1index_2 1elif val_1 val_2:index_1 1else:index_2 1return res