给你一个 m * n 的矩阵 grid,矩阵中的元素无论是按行还是按列,都以非递增顺序排列。 请你统计并返回 grid 中 负数 的数目。
Given a m x n matrix grid which is sorted in non-increasing order both row-wise and column-wise, return the number of negative numbers in grid.
示例 1:
输入:grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]]
输出:8
解释:矩阵中共有 8 个负数。
示例 2:
输入:grid = [[3,2],[1,0]]
输出:0
提示:
- m == grid.length
- n == grid[i].length
- 1 <= m, n <= 100
- -100 <= grid[i][j] <= 100
根据题意: 第一种方法: 1.获取m的值,grid.length 2.获取n的值,grid[0].length (len > 0) 3. 遍历每一项grid[i][j] ,当出现grid[i][j]< 0,num+=n-j (非递增顺序)
var countNegatives = function (grid) {
let len = grid.length
let everyLen = 0
if (len > 0) {
everyLen = grid[0].length
}
let num = 0
for (let i = 0; i < len; i++) {
for (let j = 0; j < everyLen; j++) {
if (grid[i][j] < 0) {
num += everyLen - j
break
}
}
}
return num
};
第二种方法:
ES6 之数组的flat(Infinity)扁平化,可以实现多维数组转成一维数组 //使用 Infinity 作为深度,展开任意深度的嵌套数组
var countNegatives = function (grid) {
const arr = grid.flat(Infinity);
let len = arr.length
let num = 0
for (let i = 0; i < len; i++) {
if (arr[i] < 0) {
num ++
}
}
return num
};
leetcode:https://leetcode-cn.com/problems/count-negative-numbers-in-a-sorted-matrix/
|