LeetCode刷题记录——第54题(螺旋矩阵)

版权声明:此BLOG为个人BLOG,内容均来自原创及互连网转载。最终目的为记录自己需要的内容或自己的学习感悟,不涉及商业用途,转载请附上原博客。 https://blog.csdn.net/bulo1025/article/details/89289580

题目描述

给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。

示例:

输入: [-2,1,-3,4,-1,2,1,-5,4],
输出: 6
解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。

思路分析

这个问题其实非常简单,但是我们要考虑好边界问题。

  • 黄色箭头区域【x1,x2+1】
  • 浅红色箭头区域【y1+1,y2+1】
  • 绿色箭头区域【x2-1,x1】
  • 蓝色箭头区域【y2,y1】
    在这里插入图片描述

原文:https://blog.csdn.net/qq_17550379/article/details/83148050

代码示例

class Solution(object):
    def spiralOrder(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: List[int]
        """
        result = []
        if not matrix:
            return []
        row,col = len(matrix),len(matrix[0])
        x1,x2,y1,y2 = 0,col-1,0,row-1
        while x1 <= x2 and y1 <= y2:
            for i in range(x1,x2+1):
                result.append(matrix[y1][i])
            for j in range(y1+1,y2+1):
                result.append(matrix[j][x2])
            if x1 < x2 and y1 < y2:
                for i in range(x2-1,x1,-1):
                    result.append(matrix[y2][i])
                for j in range(y2,y1,-1):
                    result.append(matrix[j][x1])
            x1 += 1
            y1 += 1
            x2 -= 1
            y2 -= 1
        return result

猜你喜欢

转载自blog.csdn.net/bulo1025/article/details/89289580