首页 > 其他 > 详细

1351. Count Negative Numbers in a Sorted Matrix

时间:2020-04-22 14:15:50      阅读:49      评论:0      收藏:0      [点我收藏+]

Problem:

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.

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

思路

当找到一个负数时,这个负数的右方和下方均为负数,则可以不用再查找。保存一个变量col为查找到每行第一个负数所在的列,这意味着下次查找的时候只需查找到col-1列,当col为0时,说明接下来的行全为负数,则可不需查找。

Solution (C++):

int countNegatives(vector<vector<int>>& grid) {
    int m = grid.size(), n = grid[0].size();
    int col = n, count = 0;
    for (int i = 0; i < m; ++i) {
        for (int j = 0; j < col; ++j) {
            if (grid[i][j] < 0) {
                count += (col-j) * (m-i);
                col = j;
                break;
            }
            if (col == 0)  break;
        }
    }
    return count;
}

性能

Runtime: 16 ms??Memory Usage: 8 MB

思路

Solution (C++):


性能

Runtime: ms??Memory Usage: MB

思路

Solution (C++):


性能

Runtime: ms??Memory Usage: MB

1351. Count Negative Numbers in a Sorted Matrix

原文:https://www.cnblogs.com/dysjtu1995/p/12751456.html

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