首页 > 其他 > 详细

1351. 统计有序矩阵中的负数

时间:2020-06-08 14:11:07      阅读:28      评论:0      收藏:0      [点我收藏+]

技术分享图片
技术分享图片
技术分享图片

方法一:二分查找。

class Solution(object):
    # 二分法
    def countNegatives(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        ans = 0
        for nums in grid:
            if nums[0] < 0:
                ans += len(nums)
                continue
            if nums[-1] >= 0:
                continue
            i, j = 0, len(nums) - 1
            while i <= j:
                mid = int(i + (j - i) / 2)
                if nums[mid] >= 0:
                    i = mid + 1
                else:
                    j = mid - 1
            if nums[i] < 0:
                ans += len(nums) - i
        return ans

方法二:暴力解。

class Solution(object):
    def countNegatives(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        ans = 0
        for i in range(len(grid)):
            if grid[i][0] < 0:
                ans += len(grid[i])
            else:
                for j in range(len(grid[i])):
                    if grid[i][j] < 0:
                        ans += 1
        return ans

1351. 统计有序矩阵中的负数

原文:https://www.cnblogs.com/panweiwei/p/13065340.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!