leetcode刷题记录1091-1100 python版

前言

继续leetcode刷题生涯
这里记录的都是笔者觉得有点意思的做法
参考了好几位大佬的题解,感谢各位大佬

1091. 二进制矩阵中的最短路径

class Solution:
    def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:
        n = len(grid)
        if not grid or grid[0][0] == 1 or grid[n-1][n-1] == 1: return -1
        elif n <= 2: return n
        q = [(0, 0, 1)]
        grid[0][0] = 1
        while q:
            i, j, step = q.pop(0)           
            for dx, dy in [(-1,-1), (1,0), (0,1), (-1,0), (0,-1), (1,1), (1,-1), (-1,1)]:
                tmp_i, tmp_j = i+dx, j+dy
                if tmp_i == n-1 and tmp_j == n-1:
                    return step + 1
                if 0 <= tmp_i < n and 0 <= tmp_j < n and grid[tmp_i][tmp_j] == 0:
                    q.append((tmp_i, tmp_j, step+1))
                    grid[tmp_i][tmp_j] = 1  # mark as visited                   
        return -1

1092. 最短公共超序列

class Solution:
    def shortestCommonSupersequence(self, str1: str, str2: str) -> str:
        n1 = len(str1)
        n2 = len(str2)
        dp = [[0 for _ in range(n2+1)] for _ in range(n1+1)] # n+1维,把俩字符串为空的情况也算上了
        # 填表格第一列, n2 = 0 的情况,另一个串多长,结果就是多长
        for i in range(n1+1):
            dp[i][0] = i
        # 填表格第一行, n1 = 0 的情况,另一个串多长,结果就是多长
        for j in range(n2+1):
            dp[0][j] = j
        for i in range(1, n1+1):
            for j in range(1, n2+1):
                if str1[i-1] == str2[j-1]: # if they match each other
                    dp[i][j] = 1 + dp[i-1][j-1]
                else:
                    dp[i][j] = 1 + min(dp[i-1][j], dp[i][j-1])

        # 回溯找路径
        res = ""
        i, j = n1, n2 # 从右下角开始回溯
        while i != 0 and j != 0:
            if str1[i-1] == str2[j-1]: # match 的话, 是从 dp图左上角来的
                print(f'i={i}, j={j}, 两边 match, 从左上角来的,添加 {str1[i-1]}')
                res = str1[i-1] + res
                i -= 1
                j -= 1
            else: # 不 match, 判断是从上面来的还是从左边来的(从二者中较小的选择中来的)
                if dp[i-1][j] < dp[i][j-1]: # 从上边来的
                    print(f'i={i}, j={j}, 两边 不 match, 从上面来的,添加{str1[i-1]}')
                    res = str1[i-1] + res
                    i -= 1
                else: # 是从左边来的
                    print(f'i={i}, j={j}, 两边 不 match, 从左面来的,添加{str2[j-1]}')
                    res = str2[j-1] + res
                    j -= 1

        # 如果有一个串先走完了
        while i != 0: # str2 先走完了, str1 还有
            res = str1[i-1] + res
            i -= 1
        while j != 0: # str1 先走完了, str2还有
            res = str2[j-1] + res
            j -= 1

        return res

1093. 大样本统计

class Solution:
    def sampleStats(self, count: List[int]) -> List[float]:
        n = sum(count)
        if n % 2 == 0:
            left_cnt, right_cnt = n//2, n//2 + 1
        else:
            left_cnt, right_cnt = n//2 + 1, n//2 + 1
        s, c = 0, 0
        max_cnt, max_cnt_index = 0, 0
        max_num, medium, min_num = 0, 0, -1
        left_flg, right_flg = False, False
        for i in range(256):
            c += count[i]
            if c >= left_cnt and not left_flg:
                medium += i
                left_flg = True
            if c >= right_cnt and not right_flg:
                medium += i
                right_flg = True
            s += count[i] * i
            if count[i] > max_cnt:
                max_cnt = count[i]
                max_cnt_index = i
            if count[i] > 0:
                max_num = i
                if min_num == -1:
                    min_num = i
        return [float(min_num), float(max_num), float(s/n), float(medium/2), float(max_cnt_index)]

1094. 拼车

class Solution:
    def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
        cap = [0] * 1001
        for num, start, end in trips:
            cap[end] -= num
            cap[start] += num  
        res = capacity 
        for i in cap:
            res -= i
            if res < 0 :
                return False
        return True

1095. 山脉数组中查找目标值

class Solution:
    def findInMountainArray(self, target: int, mountain_arr: 'MountainArray') -> int:
        # 找到山峰
        left, right = 0, mountain_arr.length() - 1
        mount_idx = 0
        while left <= right:
            mid = left + (right - left) // 2
            mid_val = mountain_arr.get(mid)
            midl_val = mountain_arr.get(mid - 1)
            midr_val = mountain_arr.get(mid + 1)
            if midl_val < mid_val and mid_val > midr_val:
                mount_idx = mid
                break
            if midl_val < midr_val:
                left = mid
            else:
                right = mid
        # 尝试在山峰左侧(递增区间)能否找到target
        left, right = 0, mount_idx
        while left <= right:
            mid = left + (right - left) // 2
            mid_val = mountain_arr.get(mid)
            if mid_val == target:
                return mid  # 如果在该循环找不到,也就不会返回,就会进入到右侧递减区间的查找
            elif mid_val > target:
                right = mid - 1
            else:
                left = mid + 1
        # 尝试在山峰右侧(递减区间)能否找到target
        left, right = mount_idx, mountain_arr.length() - 1
        while left <= right:
            mid = left + (right - left) // 2
            mid_val = mountain_arr.get(mid)
            if mid_val == target:
                return mid
            elif mid_val > target:
                left = mid + 1
            else:
                right = mid - 1
        return -1  # 如果在右侧递减区间也没能找到,则返回-1

1096. 花括号展开 II

class Solution:
    def braceExpansionII(self, expression: str) -> List[str]:
        stack,res,cur=[],[],[]
        for i in range(len(expression)):
            v=expression[i]
            if v.isalpha():
                cur=[c+v for c in cur or ['']]
            elif v=='{':
                stack.append(res)
                stack.append(cur)
                res,cur=[],[]
            elif v=='}':
                pre=stack.pop()
                preRes=stack.pop()
                cur=[p+c for c in res+cur for p in pre or ['']]
                res=preRes
            elif v==',':
                res+=cur
                cur=[]
        return sorted(set(res+cur))

猜你喜欢

转载自blog.csdn.net/weixin_44604541/article/details/108995096