第二十二条 Intersection of Two Arrays
2018-09-10 本文已影响0人
业余马拉松选手
开始第二个循环了
总归要找点好玩的事情,那么难度是在慢慢增加中,题目的数量也可以开始加加速
今天先尝试做两道题试试看
先从这道水题开始
https://leetcode-cn.com/problems/intersection-of-two-arrays-ii/description/
求两个数组的交集,这里还是先来个直接的“解法”吧
优先通过遍历其中还一个数组,用一个字典来保存每个字符出现的次数,然后再遍历第二个数组,然后依次看字典里是否有,如果有,就输出一个结果,然后对应的出现次数减一。
方法非常直接,然后有个可以稍微优化的思路,就是先遍历长度较短的那个,当然还有就是如果两个数组本来就相等的话,就干脆不用比较啦
class Solution:
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
if nums1 == nums2:
return nums1
counter = {}
ret = []
for i in nums1:
if i in counter:
counter[i] += 1
else:
counter[i] = 1
for i in nums2:
if i in counter and counter[i] > 0:
counter[i] -=1
ret.append(i)
return ret
当然还有可以用python的内置函数,或是排序等,优化的方法还是有一些的呢