原创 LeetCode 215 數組中的第K個最大元素

利用快速排序的方法解決 from typing import * class Solution: def findKthLargest(self, nums: List[int], k: int) -> int:

原创 LeetCode 673 最長遞增子序列的個數

簡單動態規劃 from typing import * class Solution: def findNumberOfLIS(self, nums: List[int]) -> int: if not nums

原创 LeetCode 1028 從先序遍歷還原二叉樹

  class Solution: def recoverFromPreorder(self, S: str) -> TreeNode: stack=[] i=0 while

原创 LeetCode 1014 最佳觀光組合

第一種方法: 找到每個下標元素右邊第一個更大的元素的下標,這一步利用棧來實現。 第二種方法,拆分成。 import sys class Solution: def maxScoreSightseeingPair(self, A:

原创 LeetCode 124 二叉樹中的最大路徑和

給定一棵非空二叉樹,返回其最大路徑和,路徑爲從任意節點出發,到達任意節點的序列,至少包含一個節點。 本道題中路徑可能彎折,因此首先要簡化,考慮從某個節點往下搜索,路徑和是多少,在考慮跨越該節點, 最大路徑和是多少。 class Solu

原创 LeetCode 297 二叉樹的序列化和反序列化

這個題難度其實不大, 利用深度優先遍歷構建字符串,同時也利用深度遍歷返回樹。 class Codec: def __init__(self): self.idx = 0 def serialize(s

原创 LeetCode 152 乘積最大子數組

動態規劃典型題目,保留最大值和最小值。 import sys class Solution: def maxProduct(self, nums: List[int]) -> int: if len(nums)=

原创 LeetCode 491 遞增子序列

搜索解決問題 注意去重 from typing import * class Solution: def __init__(self): self.res=[] def findSubsequences(

原创 LeetCode 1248 統計優美子數組

給定一個數組和整數k 如果某個子數組中恰好有k個奇數數字,認爲該數組爲優美子數組 返回優美子數組的個數 同樣是利用哈希表解決 from collections import defaultdict class Solution:

原创 LeetCode 300 最長上升子序列

給定一個整數數組,找到最長上升子序列的長度。 利用二分法,思路見官方題解。 from typing import * class Solution: def lengthOfLIS(self, nums: List[int])

原创 LeetCode 560 和爲K的子數組

很多子數組問題都採用哈希表解決。 一遍遍歷,字典中保留的是前綴和爲鍵值的下標的個數 from typing import * from collections import defaultdict class Solution:

原创 LeetCode 523 連續的子數組和

利用哈希表實現 記錄每個餘數對應的第一個位置 from typing import * class Solution: def checkSubarraySum(self, nums: List[int], k: int) ->

原创 LeetCode 1300 轉變數組後最接近目標值的數組和

參考LeetCode官網的解答。 思路: 雙重二分搜索,第一重搜索value值, value最小值爲1,最大值爲max(arr)。 找到轉變後數組和在滿足小於target的條件下的最大下標, 記爲ans,比較ans與ans加一的結果。 第

原创 LeetCode 974 和可被K整除的子數組

同樣是利用哈希表解決,哈希表鍵爲餘數,值爲前綴和整除K爲對應餘數的第一個下標。 from collections import defaultdict class Solution: def subarraysDivByK(se

原创 PAT 1053 Path of Equal Weight

Given a non-empty tree with root R, and with weight W​i​​ assigned to each tree node T​i​​. The weight of a path from R