LeetCode 1351. 统计有序矩阵中的负数 (二分、单调遍历)

统计有序矩阵中的负数
时间复杂度: O ( m l o g ( n ) ) O(m*log(n))

class Solution {
public:
    int m,n, ans = 0;
    int countNegatives(vector<vector<int>>& g) {
        m = g.size(), n = g[0].size();
        for(int i=0;i<m;i++){   
            ans += bs(g[i]);
        }
        return ans;
    }

    int bs(vector<int>& a){
        int l = 0, r = n-1 ,res = -1;
        while(l<=r){
            int mid = l+(r-l)/2;
            if(a[mid]>=0){
                res = max(res,mid);
                l = mid+1;
            }else{
                r = mid-1;
            }
        }
        return n-res-1;
    }
};

考虑到每列也是递减的,考虑每行的最后一个非负数,记它的下标为j,发现j始终只会减小。
一次遍历即可。

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

猜你喜欢

转载自blog.csdn.net/qq_44846324/article/details/107735031