46 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.

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

分析

題意:給定降序排列的二維矩陣,返回負數的個數。

顯然,題目強調矩陣是降序排列的,因此應該存在特殊的解法,而不是“直接遍歷矩陣判斷數字是否小於0就讓count++”這麼無腦。

不過,我們還是先寫一個無腦的算法吧,畢竟,先解決問題,再考慮優化。

class Solution {
    public int countNegatives(int[][] grid) {
        int count=0;
        for(int i=0;i<grid.length;++i)
            for(int j=0;j<grid[i].length;++j)
                if(grid[i][j]<0)
                    count++;
        return count;
    }
}

在這裏插入圖片描述
O(n²)時間複雜度。

也很容易想到,如果當前數字小於零,那麼後面的都小於零,沒必要遍歷了,因此可以跳過後面的遍歷。

去看看了評論區的答案,有O(m+n)的方法。

解答

class Solution {
        public int countNegatives(int[][] grid) {
        // m行n列,r表示當前行,c表示當前列
        // 初始遍歷位置爲最後一行的第一列,從“左下”往“右上”遍歷
        int m = grid.length, n = grid[0].length, r = m - 1, c = 0, res = 0;
        // 遍歷結束條件
        while (r >= 0 && c < n) {
        	// 如果當前數字小於零
            if (grid[r][c] < 0) {
            	// 就將後續的長度加到結果上
                res += n - c;
                // 並跳過當前行
                --r;
            }else {
            	// 否則就繼續查看下一個(列)數字
                ++c;
            }
        }
        return res;
    }
}

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章