Study Plan For Algorithms - Part27

WindMay發表於2024-09-10

1. 最大子陣列和
題目連結:https://leetcode.cn/problems/maximum-subarray/
給定一個整數陣列 nums ,請找出一個具有最大和的連續子陣列(子陣列最少包含一個元素),返回其最大和。

class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        if not nums:
            return 0
        max_sum = nums[0]
        current_sum = nums[0]
        for num in nums[1:]:
            current_sum = max(num, current_sum + num)
            max_sum = max(max_sum, current_sum)
        return max_sum

2. 螺旋矩陣
題目連結:https://leetcode.cn/problems/spiral-matrix/
給定一個 m 行 n 列的矩陣 matrix ,請按照 順時針螺旋順序 ,返回矩陣中的所有元素。

class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        if not matrix:
            return []
        rows = len(matrix)
        cols = len(matrix[0])
        result = []
        left, right, top, bottom = 0, cols - 1, 0, rows - 1

        while left <= right and top <= bottom:
            for i in range(left, right + 1):
                result.append(matrix[top][i])
            top += 1

            for i in range(top, bottom + 1):
                result.append(matrix[i][right])
            right -= 1

            if top <= bottom:
                for i in range(right, left - 1, -1):
                    result.append(matrix[bottom][i])
                bottom -= 1

            if left <= right:
                for i in range(bottom, top - 1, -1):
                    result.append(matrix[i][left])
                left += 1

        return result

相關文章