方法一 暴力枚举:
javascript
var countNegatives = function(grid) {
let count=0
for(let arr of grid){
for(let num of arr){
if(num<0){
count++
}
}
}
return count
};
消耗时间和内存情况:
方法二 二分法:
javascript
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;
};
消耗时间和内存情况:
方法三 双指针
javascript
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;
};
消耗时间和内存情况: