開始第二個循環(huán)了
總歸要找點好玩的事情,那么難度是在慢慢增加中,題目的數(shù)量也可以開始加加速
今天先嘗試做兩道題試試看
先從這道水題開始
https://leetcode-cn.com/problems/intersection-of-two-arrays-ii/description/
求兩個數(shù)組的交集,這里還是先來個直接的“解法”吧
優(yōu)先通過遍歷其中還一個數(shù)組,用一個字典來保存每個字符出現(xiàn)的次數(shù),然后再遍歷第二個數(shù)組,然后依次看字典里是否有,如果有,就輸出一個結(jié)果,然后對應(yīng)的出現(xiàn)次數(shù)減一。
方法非常直接,然后有個可以稍微優(yōu)化的思路,就是先遍歷長度較短的那個,當(dāng)然還有就是如果兩個數(shù)組本來就相等的話,就干脆不用比較啦
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
當(dāng)然還有可以用python的內(nèi)置函數(shù),或是排序等,優(yōu)化的方法還是有一些的呢