矩阵 metrics

发布时间 2023-06-08 09:54:47作者: xiaoyongyong
1351. Count Negative Numbers in a Sorted Matrix
Easy

Given a m x n matrix grid which is sorted in non-increasing order both row-wise and column-wise, return the number of negative numbers in grid.

 Example 1:

Input: grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]]
Output: 8
Explanation: There are 8 negatives number in the matrix.

Example 2:

Input: grid = [[3,2],[1,0]]
Output: 0

 Constraints:

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 100
  • -100 <= grid[i][j] <= 100

解法1: O(MN)

class Solution:
    def countNegatives(self, grid: List[List[int]]) -> int:
        count = 0
        def dfs(x, y):  
            if x < 0 or y < 0 or grid[x][y] >= 0:
                return
            nonlocal count
            count += 1
            grid[x][y] = 1
            dfs(x - 1, y)
            dfs(x, y - 1)
        m, n = len(grid), len(grid[0])
        dfs(m - 1, n - 1)
        return count

解法2:O(MlogN)

class Solution:
    def countNegatives(self, grid: List[List[int]]) -> int:
        def bs(row: List[int]):
            left, right = 0, len(row) - 1
            result = -1
            while left <= right:
                mid = left + (right - left) // 2
                if row[mid] >= 0:
                    left = mid + 1
                else:
                    result = mid
                    right = mid - 1
            return result
        total = 0
        for row in grid:
            pos = bs(row)
            if pos >= 0:
                total += len(row) - pos
        return total

解法3: O(M+N)

class Solution:
    def countNegatives(self, grid: List[List[int]]) -> int:
        m = len(grid[0])
        #定义最后一个不小于0的位置
        currPos = m - 1
        result = 0
        for row in grid:
            #如果小于0,那么向左移动。 
            #思考为什么要这样?因为整个矩阵是从左到右,从上到下递减的
            while currPos >= 0 and row[currPos] < 0:
                currPos -= 1
            result += m - currPos - 1
        return result