【leetcode】哈希、樹、二叉樹、堆、二叉堆入門級練習題242 49 1 94 144 590 589 429 劍指offer40 239 劍指offer49 347

242.有效的字母異位詞(亞馬遜、Facebook、谷歌在半年內面試中考過)

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        return collections.Counter(s) == collections.Counter(t)

49.字母異位詞分組(亞馬遜在半年內面試中常考)

class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        dic = {}
        for item in strs:
            key = tuple(sorted(item))
            dic[key] = dic.get(key,[]) + [item]
        return list(dic.values())

1.兩數之和(亞馬遜、字節跳動、谷歌、Facebook、蘋果、微軟、騰訊在半年內面試中常考)

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        dic = {}
        for i,num in enumerate(nums):
            if num in dic:
                return [dic[num],i]
            dic[target - num] = i

94.二叉樹的中序遍歷(亞馬遜、微軟、字節跳動在半年內面試中考過)

class Solution:
    def inorderTraversal(self, root: TreeNode) -> List[int]:
        # recursively 
        res = []
        self.helper(root,res)
        return res 
    
    def helper(self,root,res):
        if root:
            self.helper(root.left,res)
            res.append(root.val)
            self.helper(root.right,res)

144.二叉樹的前序遍歷(谷歌、微軟、字節跳動在半年內面試中考過)

class Solution:
    def preorderTraversal(self, root: TreeNode) -> List[int]:
        res = []
        self.helper(root,res)
        return res 
    
    def helper(self,root,res):
        if root:
            res.append(root.val)
            self.helper(root.left,res)
            self.helper(root.right,res)

590.N 叉樹的後序遍歷(亞馬遜在半年內面試中考過)

class Solution():
    def postorder(self, root: 'Node') -> List[int]:
        res = []
        self.helper(root,res)
        return res 

    def helper(self,root,res):
        if root:
            for child in root.children:
                self.helper(child,res)
            res.append(root.val)

589.N 叉樹的前序遍歷(亞馬遜在半年內面試中考過)

class Solution:
    def preorder(self, root: 'Node') -> List[int]:
        res = []
        self.helper(root,res)
        return res 

    def helper(self,root,res):
        if root:
            res.append(root.val)
            for child in root.children:
                self.helper(child,res)

429.N 叉樹的層序遍歷

class Solution:
    def levelOrder(self, root: 'Node') -> List[List[int]]:
        q, res = [root],[]
        while any(q):
            res.append([node.val for node in q])
            q = [child for node in q for child in node.children if child]
        return res

劍指 Offer 40. 最小的k個數(字節跳動在半年內面試中考過)

import heapq
class Solution:
    def getLeastNumbers(self, arr: List[int], k: int) -> List[int]:
        return heapq.nsmallest(k,arr)

239.滑動窗口最大值(亞馬遜在半年內面試中常考)

class Solution:
    def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
        d = collections.deque()
        out = []
        for i,n in enumerate(nums):
            while d and nums[d[-1]] < n:
                d.pop()
            d.append(i)
            if d[0] == i - k:
                d.popleft()
            if i >= k - 1:
                out.append(nums[d[0]])
        return out

劍指 Offer 49. 醜數(字節跳動在半年內面試中考過)
法一:最小堆的方法 O(n logn)
法二:動態規劃的辦法

# 法一:
import heapq
class Solution:
    def nthUglyNumber(self, n: int) -> int:
        h = [(1, 1)]
        for _ in range(n):
        # heapq.heappop(heap):將heap的最小值pop出heap,heap爲空時報IndexError錯誤
            val, fact = heapq.heappop(h)  
            for x in 2, 3, 5:
                if fact <= x:
                  # heapq.heappush(heap,item):將item,推入heap
                    heapq.heappush(h, (val * x, x))  
        return val
# 法二:動態規劃
class Solution:
    def nthUglyNumber(self, n: int) -> int:
        dp,a,b,c = [1] * n,0,0,0
        for i in range(1,n):
            n2,n3,n5 = dp[a] * 2,dp[b] * 3,dp[c] * 5
            dp[i] = min(n2,n3,n5)
            if dp[i] == n2:a += 1
            if dp[i] == n3:b += 1
            if dp[i] == n5:c += 1
        return dp[-1]

347.前 K 個高頻元素(亞馬遜在半年內面試中常考)

import collections 
import heapq
class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        count_num = collections.Counter(nums)
        return heapq.nlargest(k,count_num,key = lambda x:count_num[x])
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章