leetcode 1351. 统计有序矩阵中的负数 js实现
2023-09-14 09:07:43 时间
给你一个 m * n
的矩阵 grid
,矩阵中的元素无论是按行还是按列,都以非递增顺序排列。 请你统计并返回 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
https://leetcode.cn/problems/count-negative-numbers-in-a-sorted-matrix/description/
/** * @param {number[][]} grid * @return {number} */ // 暴力解法 // var countNegatives = function(grid) { // let count = 0; // if(grid.length===0 || grid[0].length===0){ // return count // } // for(let i=0;i<grid.length;i++){ // for(let j=0;j<grid[0].length;j++){ // if(grid[i][j]<0){ // count++ // } // } // } // return count // };
// 二分查找 var countNegatives = function(grid) { let count = 0; if(grid.length===0 || grid[0].length===0){ } for(let i=0;i<grid.length;i++){ for(let j=0;j<grid[0].length;j++){ // 因为是递减排序,当当前元素已经小于0,说明之后的元素都小于0,则直接将之后的所有元素的数量进行赋值 if(grid[i][j]<0){ count+=grid[0].length-j; // 并跳出此次循环 break; } } } return count };
相关文章
- leetcode 415. 字符串相加 js 实现
- leetcode 78. 子集 js 实现
- ☆打卡算法☆LeetCode 205. 同构字符串 算法解析
- LeetCode笔记:Weekly Contest 311
- <leetcode刷题-数组>删除排序数组中的重复项
- 使用 Dapr JS SDK 让 Nest.js 集成 Dapr(微软开源的分布式应用程序运行时)
- LeetCode–046–全排列(java)
- LeetCode每日一题06-16
- leetcode-76最小覆盖子串(双指针)
- leetcode 136. 只出现一次的数字 js 实现
- LeetCode 235. 二叉搜索树的最近公共祖先
- leetcode 206. 反转链表 js实现
- 前端工程师leetcode算法面试必备-二叉树的构造和遍历
- Vue.js – 引入外部 JS 文件
- leetcode 160. 相交链表 js 实现
- leetcode 54. 螺旋矩阵 js高效实现
- js分类刷leetcode动态规划
- LeetCode - #68 文本左右对齐
- LeetCode周赛323,LeetCode官方的福利专场
- LeetCode-283-移动零
- Leetcode 560. 和为 K 的子数组
- 「动态规划」LeetCode 70(爬楼梯)