每日一题——LeetCode1351.统计有序矩阵中的负数

每日一题——LeetCode1351.统计有序矩阵中的负数_第1张图片

方法一 暴力枚举:

var countNegatives = function(grid) {
    let count=0
    for(let arr of grid){
        for(let num of arr){
            if(num<0){
                count++
            }
        }
    }
    return count
};

消耗时间和内存情况:

每日一题——LeetCode1351.统计有序矩阵中的负数_第2张图片

方法二 二分法:

var countNegatives = function(grid) {
    const m = grid.length;  
    const n = grid[0].length;  
    let count = 0;  
    for (let i = 0; i < m; i++){
        let row = grid[i];  
        let left = 0;
        let right = n - 1;
        while(left <= right){
            let mid = Math.floor(left + (right - left) / 2);
            if (row[mid] < 0){  
                right = mid - 1;
            }else if (row[mid] > 0){  
                left = mid + 1;
            }else if (row[mid] === 0){
                left = mid + 1;
            }
        }
        count += n - left;
    }
    return count;
};

消耗时间和内存情况:

每日一题——LeetCode1351.统计有序矩阵中的负数_第3张图片

方法三 双指针

var countNegatives = function(grid) {
    let row = 0;
    let col = grid[0].length - 1;
    let num = 0;
    while(row < grid.length && col >=0){
        if(grid[row][col] < 0){
            num = num + (grid.length - row);
            col = col - 1;
        }else{
            row = row + 1;
        }
    }
    return num;
};

 消耗时间和内存情况:

每日一题——LeetCode1351.统计有序矩阵中的负数_第4张图片

你可能感兴趣的:(每日一题,javascript,算法,leetcode)