Skip to content

Latest commit

 

History

History
157 lines (127 loc) · 3.17 KB

File metadata and controls

157 lines (127 loc) · 3.17 KB

中文文档

Description

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

Example 3:

Input: grid = [[1,-1],[-1,-1]]
Output: 3

Example 4:

Input: grid = [[-1]]
Output: 1

 

Constraints:

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

 

Follow up: Could you find an O(n + m) solution?

Solutions

Python3

class Solution:
    def countNegatives(self, grid: List[List[int]]) -> int:
        m, n, cnt = len(grid), len(grid[0]), 0
        i, j = 0, n - 1
        while i < m and j >= 0:
            if grid[i][j] < 0:
                cnt += (m - i)
                j -= 1
            else:
                i += 1
        return cnt

Java

class Solution {
    public int countNegatives(int[][] grid) {
        int m = grid.length, n = grid[0].length;
        int cnt = 0;
        for (int i = 0, j = n - 1; j >= 0 && i < m;) {
            if (grid[i][j] < 0) {
                cnt += (m - i);
                --j;
            } else {
                ++i;
            }
        }
        return cnt;
    }
}

TypeScript

function countNegatives(grid: number[][]): number {
    let m = grid.length, n = grid[0].length;
    let i = 0, j = n - 1;
    let ans = 0;
    while (i < m && j > -1) {
        let cur = grid[i][j];
        if (cur < 0) {
            j--;
            ans += (m - i);
        } else {
            i++;
        }
    }
    return ans;
};

C++

class Solution {
public:
    int countNegatives(vector<vector<int>>& grid) {
        int m = grid.size(), n = grid[0].size();
        int i = 0, j = n - 1, cnt = 0;
        while (i < m && j >= 0) {
            if (grid[i][j] < 0) {
                cnt += (m - i);
                --j;
            } else {
                ++i;
            }
        }
        return cnt;
    }
};

Go

func countNegatives(grid [][]int) int {
	m, n := len(grid), len(grid[0])
	i, j, cnt := 0, n-1, 0
	for i < m && j >= 0 {
		if grid[i][j] < 0 {
			cnt += (m - i)
			j--
		} else {
			i++
		}
	}
	return cnt
}

...