【LeetCode热题100】

这篇博客涵盖了多个LeetCode热门题目,包括括号生成、最小覆盖子串、三数之和等,涉及二叉树、岛屿问题、滑动窗口、数组和链表操作,以及动态规划和数据结构的运用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

LeetCode热题100

22. 括号生成(🎂)

class Solution:
    def generateParenthesis(self, n: int) -> List[str]:
        res = []

        def backtracking(S, left, right):
            if len(S) == 2*n:
                res.append(''.join(S))
                return
            
            if left < n:
                S.append('(')
                backtracking(S, left+1, right)
                S.pop()
            
            # 这里是右括号的数目要小于左括号的数目
            if right < left:
                S.append(')')
                backtracking(S, left, right+1)
                S.pop()
        
        backtracking([], 0, 0)
        return res

76. 最小覆盖子串(🎂)

class Solution:
    def minWindow(self, s: str, t: str) -> str:
        m, n = len(s), len(t)
        if m < n: return ''
        
        dic_t = collections.Counter(t)

        def is_in(dic, dic_t):
            for k, v in dic_t.items():
                if dic[k] <= 0: return False
                if dic[k] < dic_t[k]: return False
            return True

        dic = collections.defaultdict(int)
        l, r = 0, 0
        min_length = float('inf')
        res = ''

        while r < m:
            while r < m and not is_in(dic, dic_t):
                dic[s[r]] += 1
                r += 1
            
            while l < r and is_in(dic, dic_t):
                if r-l < min_length:
                    min_length = r - l
                    res = s[l:r]
                dic[s[l]] -=1 
                l += 1
        
        return res

15. 三数之和(🎂)

class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        # 使用双指针的解法,可以使得复杂度降低到O(n^2)
        res, k = [], 0
        nums.sort()

        for k in range(len(nums) - 2):
            if nums[k] > 0: break
            if k > 0 and nums[k] == nums[k-1]: continue
            l, r = k+1, len(nums) - 1            
            while l < r:
                s = nums[k] + nums[l] + nums[r]
                if s < 0:
                    # 太小了,右移左指针
                    l += 1
                    while l < r and nums[l] == nums[l-1]: l += 1
                elif s > 0:
                    # 太大了,减小右指针
                    r -= 1
                    while l < r and nums[r] == nums[r+1]: r -= 1
                else:
                    # 刚刚好
                    res.append([nums[k], nums[l], nums[r]])
                    # 可以趁机继续剪枝
                    l += 1
                    r -= 1
                    while l < r and nums[l] == nums[l-1]: l += 1
                    while l < r and nums[r] == nums[r+1]: r -= 1
                    

        return res

105. 从前序与中序遍历序列构造二叉树(🎂)

class Solution:
    def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
        # 先序遍历的第一个元素肯定是根节点, [根节点, 左子树, 右子树]
        # 中序遍历的结果是,[左子树,根节点,右子树]
        # 因此,第一步先通过先序遍历的第一个元素找到根节点,再在中序遍历中找到根节点所对应的位置,
        if not preorder: return None
        
        root_val = preorder[0]
        root = TreeNode(root_val)

        seperate_idx = inorder.index(root_val)
        left_inorder = inorder[:seperate_idx]
        right_inorder = inorder[seperate_idx+1:]

        left_preorder = preorder[1:1+len(left_inorder)]
        right_preorder = preorder[1+len(left_inorder):]

        root.left = self.buildTree(left_preorder, left_inorder)
        root.right = self.buildTree(right_preorder, right_inorder)

        return root

此外,从三种遍历中任意取两个出来,都可以恢复这个二叉树。

56. 合并区间(🎂)

class Solution:
    def merge(self, intervals: List[List[int]]) -> List[List[int]]:
        n = len(intervals)
        if n < 2: return intervals

        intervals = sorted(intervals, key=lambda x: x[0]) # 按照左边界进行排序
        res = []
        l, r = 0, 1
        while r < n:
            left = intervals[l][0]
            right = intervals[l][1]

            while r < n and intervals[r][0] <= right:
                right = max(intervals[r][1], right)
                r += 1
            res.append([left, right])

            l = r
            r += 1
        
        if l == n - 1:
            res.append(intervals[l])
        
        return res

200. 岛屿数量

class Solution:
    def numIslands(self, grid: List[List[str]]) -> int:
        def dfs(i, j):
            # 终止条件
            if not (0 <= i < len(grid)) or not (0 <= j < len(grid[0])): return
            if grid[i][j] == '0': return


            # 内部逻辑
            grid[i][j] = '0' # 淹没该陆地
            up = dfs(i-1, j)
            down = dfs(i+1, j)
            left = dfs(i, j-1)
            right = dfs(i, j+1)

            return 

        m, n = len(grid), len(grid[0])

        res = 0
        for i in range(m):
            for j in range(n):
                if grid[i][j] == '1':
                   dfs(i, j)
                   res += 1 

        return res

105. 岛屿的最大面积

class Solution:
    def maxAreaOfIsland(self, grid: List[List[int]]) -> int:

        def dfs(i, j):
            if not (0 <= i < len(grid)) or not (0 <= j < len(grid[0])): return 0
            if grid[i][j] == 0: return 0

            # 内部逻辑
            grid[i][j] = 0  # 淹没陆地
            return 1 + dfs(i-1, j) + dfs(i+1, j) + dfs(i, j-1) + dfs(i, j+1)
        m, n = len(grid), len(grid[0])

        res = 0
        for i in range(m):
            for j in range(n):
                if grid[i][j] == 1:
                    area = dfs(i, j)
                    res = max(res, area)
        
        return res

463. 岛屿的周长(🎂)

class Solution:
    def islandPerimeter(self, grid: List[List[int]]) -> int:
        res = 0
        m, n = len(grid), len(grid[0])
        for i in range(m):
            for j in range(n):
                if grid[i][j] == 1:
                    res += 4
                    # 如果上下左右有相邻的陆地,有一块就要减去1
                    for dx, dy in [[-1, 0], [1, 0], [0, -1], [0, 1]]:
                        x, y = i + dx, j + dy
                        if 0 <= x < m and 0 <= y < n and grid[x][y] == 1:
                            res -= 1
    
        return res

如果有多块陆地,下面的递归方法稍微改一下,价格计数器,每次dfs完把当前岛的周长加到计数器上,最后一起返回就行了。

class Solution:
    def islandPerimeter(self, grid: List[List[int]]) -> int:
        def dfs(i, j):
            if not (0 <= i < len(grid)) or not (0 <= j < len(grid[0])): return 1 # 边界
            if grid[i][j] == 0: return 1 # 水
            if grid[i][j] != 1: return 0 # 走过了
            
            grid[i][j] = 2 # 走过的路标记一下

            return dfs(i-1, j) + dfs(i+1, j) + dfs(i, j-1) + dfs(i, j+1)
        
        for i in range(len(grid)):
            for j in range(len(grid[0])):
                if grid[i][j] == 1:
                    return dfs(i, j)

827. 最大人工岛(🎂)

239. 滑动窗口最大值

class Solution:
    def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
        q = [(-nums[i], i) for i in range(k)]
        heapq.heapify(q)

        res = [-q[0][0]]
        n = len(nums)
        for i in range(k, n):
            heapq.heappush(q, (-nums[i], i))
            while q[0][1] <= i - k:
                heapq.heappop(q)

            res.append(-q[0][0])
        return res
class Solution:
    def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
        q = []
        for i in range(k):
            while q and nums[i] >= nums[q[-1]]:
                q.pop()
            q.append(i)
        
        res = [nums[q[0]]]
        for i in range(k, len(nums)):
            while q and nums[i] >= nums[q[-1]]:
                q.pop()
            q.append(i)
            while q and q[0] <= i - k:
                q.pop(0)
            
            res.append(nums[q[0]])
        
        return res

17. 电话号码的字母组合

class Solution:
    def letterCombinations(self, digits: str) -> List[str]:
        if not digits: return []
        
        dic = {
   '2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno',
        '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}

        paths, path = [], []
        def backtracking(i, path):
            if len(path) >= len(digits): 
                paths.append(''.join(path))
                return
            
            for digit in dic[digits[i]]:
                path.append(digit)
                backtracking(i+1, path)
                path.pop()
            
        backtracking(0, path)

        return paths

75. 颜色分类

class Solution:
    def sortColors(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        def quickSort(i, j):
            if i 
### LeetCode 100 LeetCode 上的目列表通常包含了社区中最受欢迎和频繁被讨论的问。这些目不仅有助于提升编程技能,也是求职者准备技术面试的重要资源。 #### 两数之和 该问是关于在一个整数数组中寻找两个数,使它们的和等于给定的目标数值[^1]。 ```python def two_sum(nums, target): num_to_index = {} for index, num in enumerate(nums): another_num = target - num if another_num in num_to_index: return [num_to_index[another_num], index] num_to_index[num] = index return [] ``` #### 合并两个有序链表 此问涉及将两个升序链表合并为一个新的升序链表,新链表由原两个链表中的节点组成。 ```python class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def merge_two_lists(l1, l2): dummy = cur = ListNode(0) while l1 and l2: if l1.val < l2.val: cur.next = l1 l1 = l1.next else: cur.next = l2 l2 = l2.next cur = cur.next cur.next = l1 or l2 return dummy.next ``` #### 最长回文子串 这个问旨在找出字符串 `s` 中最长的回文子串。解决方案可以基于中心扩展方法或动态规划实现[^2]。 ```python def longest_palindromic_substring(s): if not s: return "" start, end = 0, 0 for i in range(len(s)): len1 = expand_around_center(s, i, i) len2 = expand_around_center(s, i, i + 1) max_len = max(len1, len2) if max_len > end - (max_len - 1) // 2 end = i + max_len // 2 return s[start:end + 1] def expand_around_center(s, left, right): L, R = left, right while L >= 0 and R < len(s) and s[L] == s[R]: L -= 1 R += 1 return R - L - 1 ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值