首页 > 其他分享 >LeetCode Hot 100

LeetCode Hot 100

时间:2024-09-23 13:51:39浏览次数:8  
标签:head return self fast next Hot 100 LeetCode def

1 Tree

1.1 Recursion


1.1 Recursion

PreOrderTraversal

https://leetcode.cn/problems/binary-tree-preorder-traversal/

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        self.res = []
        def dfs(node):
            if node is None:
                return
            self.res.append(node.val)
            dfs(node.left)
            dfs(node.right)
        dfs(root)
        return self.res

InOrderTraversal

https://leetcode.cn/problems/binary-tree-inorder-traversal/


PostOrderTraversal

https://leetcode.cn/problems/binary-tree-inorder-traversal/


二叉树的最大深度


二叉树的直径


1.2 LevelOrderTraversal

https://leetcode.cn/problems/binary-tree-level-order-traversal/

class Solution:
    def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
        if root is None:
            return []
        ans = []
        from collections import deque
        q = deque([root])
        while q:
            tmp = []
            for _ in range(len(q)): # for loop [], until it's full
                node = q.popleft()
                tmp.append(node.val)
                if node.left: q.append(node.left)
                if node.right: q.append(node.right)
            ans.append(tmp)
        return ans

https://leetcode.cn/problems/binary-tree-zigzag-level-order-traversal/

class Solution:
    def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
        if root is None:
            return []
        ans = []
        from collections import deque
        q = deque([root])
        while q:
            tmp = []
            for _ in range(len(q)): # for loop [], until it's full
                node = q.popleft()
                tmp.append(node.val)
                if node.left: q.append(node.left)
                if node.right: q.append(node.right)
            ans.append(tmp[::-1] if len(ans)%2 else tmp)
        return ans

https://leetcode.com/problems/find-bottom-left-tree-value/

class Solution:
    def findBottomLeftValue(self, root: Optional[TreeNode]) -> int:
        if root is None:
            return
        from collections import deque
        q = deque([root])
        tmp = []
        while q:
            node = q.popleft()
            tmp.append(node.val)
            if node.right: q.append(node.right)
            if node.left: q.append(node.left)
        return tmp[-1]

1.3 BST

BST(Binary Search Tree),二叉搜索树具有左子树 < Root < 右子树的性质。

https://leetcode.cn/problems/convert-sorted-array-to-binary-search-tree/?envType=study-plan-v2&envId=top-100-liked

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
        def dfs(nums, lo, hi):
            if lo > hi: return
        # 以升序数组的中间元素作为根节点 root
            mid = lo + (hi - lo) // 2
            root = TreeNode(nums[mid])
            root.left = dfs(nums, lo, mid - 1)
            root.right = dfs(nums, mid + 1, hi)
            return root
        return dfs(nums, 0, len(nums)-1)

1.4 Common Ancestor

https://leetcode.cn/problems/er-cha-shu-de-zui-jin-gong-gong-zu-xian-lcof/


https://leetcode.cn/problems/er-cha-sou-suo-shu-de-zui-jin-gong-gong-zu-xian-lcof/


2 Sliding Window

https://leetcode.cn/problems/longest-substring-without-repeating-characters/

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        ans = 0
        cnt = Counter()
        left = 0
        for right, c in enumerate(s): # add the new character to the s, from right
            cnt[c] += 1
            while cnt[c] > 1: # abcb -> bcb -> cb
                cnt[s[left]] -= 1
                left += 1
            ans = max(ans, right - left + 1)
        return ans

https://leetcode.cn/problems/find-all-anagrams-in-a-string

class Solution:
    def findAnagrams(self, s: str, p: str) -> List[int]:
        n, m, res = len(s), len(p),[]
        if n < m: return res
        p_cnt = [0] * 26
        s_cnt = [0] * 26
        for i in range(m): # initialize p_cnt
            p_cnt[ord(p[i]) - ord("a")] += 1
            s_cnt[ord(s[i]) - ord("a")] += 1
        if s_cnt == p_cnt:
            res.append(0)

        for i in range(m,n): # sliding window
            s_cnt[ord(s[i-m])-ord("a")] -= 1
            s_cnt[ord(s[i])-ord("a")] += 1
            if s_cnt == p_cnt:
                res.append(i-m+1) # start index
        return res

3 Prefix Sum

https://leetcode.cn/problems/range-sum-query-immutable/


https://leetcode.cn/problems/subarray-sum-equals-k/

  • 计算前缀和s,注意要初始化一个0,
  • 因为s[j] - s[i] = k,所以s[j] - k = s[i]
  • 每次寻找 s[j] 前面有多少个前缀和等于 s[j]−k, 用哈希表记录前缀和的个数,就能 O(1) 算出前面有多少个 s[j]−k
  • 遍历前缀和s, ans += cnt[s[j] - k], cnt[s[i]] += 1,顺序不能颠倒,因为如果k=0,会多记一次
class Solution:
    def subarraySum(self, nums: List[int], k: int) -> int:
        s = [0] * (len(nums) + 1)
        for i, num in enumerate(nums):
            s[i+1] = s[i] + num

        ans = 0
        cnt = Counter()
        for sj in s:
            ans += cnt[sj - k]
            cnt[sj] += 1

        return ans

4 Stack

https://leetcode.cn/problems/valid-parentheses/

class Solution:
    def isValid(self, s: str) -> bool:
        if len(s)%2 != 0:
            return False
        mp = {"}":"{", ")":"(", "]":"["}
        st = []
        for c in s:
            if c not in mp: # c是左括号
                st.append(c)
            elif not st or st.pop() != mp[c]: # c是右括号
                return False # 没有左括号,或右括号不匹配
        return not st # 所有左括号必须匹配完毕,检查左括号比右括号多的情况,如{{}

5 Linked List

5.1 反转链表

206.反转链表: https://leetcode.cn/problems/reverse-linked-list/

  • 初始化:pre指向null,cur指向head
  • 先暂存head.next,再改变head.next,最后更新head
    • tmp = cur.next
    • cur.next = pre
    • pre = cur
    • cur = tmp
  • 必记性质:反转结束后,pre指向这一段的末尾,cur指向这一段末尾的下一个节点
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        pre, cur = None, head
        while cur:
            tmp = cur.next
            cur.next = pre
            pre = cur
            cur = tmp
        return pre

5.2 快慢指针

https://leetcode.cn/problems/middle-of-the-linked-list/

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
        slow = head
        fast = head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
        return slow

https://leetcode.cn/problems/linked-list-cycle/

  • 关注fast和slow的相对运动,相当于fast相对运动一格,如果有环,最终fast肯定会与slow相遇
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def hasCycle(self, head: Optional[ListNode]) -> bool:
        slow = head
        fast = head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
            if fast is slow:
                return True
        return False

https://leetcode.cn/problems/linked-list-cycle-ii/

  • 哈希表记录遍历过的节点, 记录大于2表示有环,且为入口
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
        visited = Counter()
        while head:
            if visited[head]:
                return head
            visited[head] += 1
            head = head.next
        return None

Follow up: Can you solve it using O(1) (i.e. constant) memory?

  • 最差情况: 当慢指针进入环时,快指针刚好在慢指针前面,根据相对距离分析,快指针需要走(环长-1)步的相对距离才能追上慢指针,其余任何情况快指针走的步数都小于(环长-1),所以慢指针移动的距离是小于环长的。
  • slwo和fast相遇之后:head从出发点出发,slow从相遇点出发,head和slow相遇的位置必定是入口,这是因为设相遇点到入口的距离为c, a - c = (k - 1)(b + c)
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
        slow = head
        fast = head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
            if fast is slow: # 有环
                while slow is not head:
                    slow = slow.next
                    head = head.next
                return slow
        return None

https://leetcode.cn/problems/reorder-list/

  • 找到链表中点,反转链表
  • 先暂存head.next,再改变head.next,最后更新head
    • tmp = head.next
    • tmp2 = head2.next
    • head.next = head2
    • head2.next = tmp
    • head = tmp
    • head2 = tmp2
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def middleNode(self, head):
        slow = head
        fast = head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
        return slow

    def reverseList(self, head):
        pre = None
        cur = head
        while cur:
            tmp = cur.next
            cur.next = pre
            pre = cur
            cur = tmp
        return pre

    def reorderList(self, head: Optional[ListNode]) -> None:
        mid = self.middleNode(head)
        head2 = self.reverseList(mid)

        while head2.next:
            tmp = head.next
            tmp2 = head2.next
            head.next = head2
            head2.next = tmp
            head = tmp
            head2 = tmp2

https://leetcode.cn/problems/palindrome-linked-list/

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def middleNode(self, head):
        slow = head
        fast = head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
        return slow

    def reverseList(self, head):
        pre = None
        cur = head
        while cur:
            tmp = cur.next
            cur.next = pre
            pre = cur
            cur = tmp
        return pre

    def isPalindrome(self, head: Optional[ListNode]) -> bool:
        if head is None:
            return True

        mid = self.middleNode(head)
        head2 = self.reverseList(mid)
        while head2:
            if head.val != head2.val:
                return False
            head = head.next
            head2 = head2.next
        return True

5.3 前后指针

https://leetcode.cn/problems/intersection-of-two-linked-lists/

  • 初始化:A指向headA,B指向headB,同时开始向前遍历
  • 遍历: a + (b - c) = b + (a - c)
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:
        A = headA
        B = headB
        while A!=B:
            A = A.next if A else headB
            B = B.next if B else headA
        return A

标签:head,return,self,fast,next,Hot,100,LeetCode,def
From: https://www.cnblogs.com/forhheart/p/18417822

相关文章

  • Leetcode 65. 有效数字
    1.题目基本信息1.1.题目描述给定一个字符串s,返回s是否是一个有效数字。例如,下面的都是有效数字:”2″,“0089”,“-0.1”,“+3.14”,“4.”,“-.9”,“2e10”,“-90E3”,“3e+7”,“+6e-1”,“53.5e93”,“-123.456e789″,而接下来的不是:”abc”,“1a”,“1e”......
  • 100个句子记完7000个雅思单词 实际只有约1400个词汇
    en:"Thereisconsiderabledebateoverhowweshouldreactifwedetectasignalfromanaliencivilization.",cn:"如果我们探测到了来自外星文明的信号,我们应该如何回应是一个备受争议的问题。"en:"Thetwoworldwars,whichinterruptedthesupplyofrawmateria......
  • 英特尔®以太网网络适配器E810-CQDA1 / E810-CQDA2 网卡 规格书 e810 网卡 规格书 Int
    英特尔®以太网800系列网络适配器英特尔®以太网网络适配器E810-CQDA1/CQDA2在10到100Gbps的以太网速度下实现高效的工作负载优化性能关键特性•单、双端口QSFP28•应用设备队列(ADQ)•PCIExpress(PCIe)4.0x16•动态设备个性化(DDP)•以太网端口配置工具(EPCT)......
  • 题单2:基础练习(1000~1400)
    概述每组题单由7道题组成,难度为:1000(1),1100(2),1200(2),1300(1),1400(1)第五周9.30~10.6500A.NewYearTransportation467B.FedorandNewGame82A.DoubleCola1541B.PleasantPairs1832C.ContrastValue520B.TwoButtons数学230B.T-pri......
  • 计算机低能儿从0刷leetcode | 11.盛最多水的容器
    题目:11.盛最多水的容器解答:不想暴力遍历,于是让右端点j从最右侧开始遍历,每次寻找离j最远、且高度不小于height[j]的左端点i,结果发现错误,比如[1,2]的情况。于是又打补丁,按同样思路左端点i从0开始遍历,每次寻找离i最远、且高度不小于height[i]的右端点j,结果正确,然而时间复杂度......
  • 数据结构之线性表——LeetCode:328. 奇偶链表,86. 分隔链表,24. 两两交换链表中的节点
    328.奇偶链表题目描述328.奇偶链表给定单链表的头节点 head ,将所有索引为奇数的节点和索引为偶数的节点分别组合在一起,然后返回重新排序的列表。第一个节点的索引被认为是 奇数 , 第二个节点的索引为 偶数 ,以此类推。请注意,偶数组和奇数组内部的相对顺序应该与输......
  • 数据结构之线性表——LeetCode:80. 删除有序数组中的重复项 II,88. 合并两个有序数组,4.
    80.删除有序数组中的重复项II题目描述80.删除有序数组中的重复项II给你一个有序数组 nums ,请你 原地 删除重复出现的元素,使得出现次数超过两次的元素只出现两次 ,返回删除后数组的新长度。不要使用额外的数组空间,你必须在 原地 修改输入数组 并在使用O(1)额外......
  • 数据结构之线性表——LeetCode:82. 删除排序链表中的重复元素 II,21. 合并两个有序链
    82.删除排序链表中的重复元素II题目描述82.删除排序链表中的重复元素II给定一个已排序的链表的头 head , 删除原始链表中所有重复数字的节点,只留下不同的数字 。返回 已排序的链表 。运行代码classSolution{public:ListNode*deleteDuplicates(ListNode......
  • LeetCode力扣——并查集:947. 移除最多的同行或同列石头,1971. 寻找图中是否存在路径,24
    947.移除最多的同行或同列石头题目描述947.移除最多的同行或同列石头n 块石头放置在二维平面中的一些整数坐标点上。每个坐标点上最多只能有一块石头。如果一块石头的 同行或者同列 上有其他石头存在,那么就可以移除这块石头。给你一个长度为 n 的数组 stones ,其......
  • P5975 photo 题解
    Solution先离散化,记\(f(l,r,p)\)为覆盖了\([l,r]\)区间内纵坐标\(\gep\)的点最少矩形个数。则:\[f(l,r,p)=\min(f(l,r,p),f(l,mid,p)+f(mid+1,r,p))\]\[f(l,r,p)=\min(f(l,r,p),f(l,r,res)+1)\]令\(h\)为用面积为\(S\)的矩形去覆盖\([l,r]\)区间的高度,即\(S/(r......