Study Plan For Algorithms - Part40

1. 单词搜索
给定一个 m x n 二维字符网格 board 和一个字符串单词 word 。如果 word 存在于网格中,返回 true ;否则,返回 false 。

class Solution:
    def exist(self, board: List[List[str]], word: str) -> bool:
        rows = len(board)
        cols = len(board[0])
        visited = [[False for _ in range(cols)] for _ in range(rows)]

        def dfs(i, j, index):
            if index == len(word):
                return True
            if i < 0 or i >= rows or j < 0 or j >= cols or visited[i][j] or board[i][j]!= word[index]:
                return False
            visited[i][j] = True
            found = dfs(i + 1, j, index + 1) or dfs(i - 1, j, index + 1) or dfs(i, j + 1, index + 1) or dfs(i, j - 1, index + 1)
            visited[i][j] = False
            return found

        for i in range(rows):
            for j in range(cols):
                if dfs(i, j, 0):
                    return True
        return False

2. 删除有序数组中的重复项 II
给定一个有序数组 nums ,原地 删除重复出现的元素,使得出现次数超过两次的元素只出现两次 ,返回删除后数组的新长度。

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        i = 0
        for num in nums:
            if i < 2 or num > nums[i - 2]:
                nums[i] = num
                i += 1
        return i
posted @ 2024-09-23 02:26  WindMay  阅读(4)  评论(0编辑  收藏  举报