Leetcode 1351. 统计有序矩阵中的负数 题解

题目链接:https://leetcode-cn.com/problems/count-negative-numbers-in-a-sorted-matrix/
在这里插入图片描述
在这里插入图片描述
暴力法是 O(mn) 的复杂度,即一个一个遍历算count

写一个二分函数findn找每行的第一个负值元素,并将其下标返回,作为下一行二分查找的右指针起始点。复杂度为O(m * lgn)

代码如下:

class Solution {
public:
    int findn(vector<int> v, int r) {
        int l = 0;
        while(l <= r) {
            int mid = (l + r) / 2;
            if(v[mid] < 0) {
                r = mid - 1;
            } else {
                l = mid + 1;
            }
        }
        return l;
    }
    
    int countNegatives(vector<vector<int>>& grid) {
        int res = 0;
        int len = grid[0].size();
        int pos = len;
        for(int i = 0; i < grid.size(); i++) {
            pos = findn(grid[i], pos - 1);
            res += len - pos;
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_42396397/article/details/105925708