1351. Count Negative Numbers in a Sorted Matrix

Given a m * n matrix grid which is sorted in non-increasing order both row-wise and column-wise. 

Return the number of negative numbers in grid.

每行是不递减的顺序,每列也是不递减的顺序,统计有多少格子是负数

n2方法 两层for循环

nlog方法 对每一行做二分搜索

class Solution(object):
    def countNegatives(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        cnt = 0
        for row in grid:
            l = 0
            r = len(row) - 1
            while l <= r:
                mid = (l + r) // 2
                if row[mid] < 0:
                    r = mid - 1
                else:
                    l = mid + 1
            cnt += len(row) - l
        return cnt
            
        

n+m方法 利用行列都是有序的性质,从最左下角开始,每行先往右走,找到第一个负数的位置,然后统计一下,然后往上一行继续重复之前的操作。

class Solution(object):
    def countNegatives(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        cnt = 0
        n = len(grid)
        m = len(grid[0])
        row = n - 1
        col = 0
        while row >= 0:
            while col < m:
                if grid[row][col] >= 0:
                    col += 1
                else:
                    break
            cnt += m - col
            row -= 1
        return cnt
            
        
原文地址:https://www.cnblogs.com/whatyouthink/p/13207046.html