74. Search a 2D Matrix
来源:互联网 发布:宁夏广电网络总经理 编辑:程序博客网 时间:2024/06/05 11:51
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
Integers in each row are sorted from left to right.
The first integer of each row is greater than the last integer of the previous row.
For example,
Consider the following matrix:
[ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50]]
Given target = 3, return true.
题意:先求出在哪行,问题等价于求第一个小于等于target的数.
然后用正常的二分查找。
class Solution {public: bool searchMatrix(vector<vector<int>>& matrix, int target) { if(matrix.empty() || matrix[0].empty()) return false; int mid, l, r, line = matrix.size(); l = 0, r = matrix.size() - 1; while(l <= r){ mid = l + (r - l) / 2; if(matrix[mid][0] == target){ return true; } else if(matrix[mid][0] > target){ r = mid - 1; } else if(matrix[mid][0] < target){ l = mid + 1; } } if(r < 0) return false; else line = r; l = 0, r = matrix[0].size() - 1; while(l <= r){ mid = l + (r - l) / 2; if(matrix[line][mid] == target) return true; else if(matrix[line][mid] > target){ r = mid - 1; } else if(matrix[line][mid] < target) l = mid + 1; } return false; }};
阅读全文
0 0
- LeetCode 74. Search a 2D Matrix
- [LeetCode]74.Search a 2D Matrix
- LeetCode --- 74. Search a 2D Matrix
- [Leetcode] 74. Search a 2D Matrix
- [leetcode] 74.Search a 2D Matrix
- 74. Search a 2D Matrix
- 74. Search a 2D Matrix
- Leetcode 74. Search a 2D Matrix
- [LeetCode]74. Search a 2D Matrix
- 74. Search a 2D Matrix LeetCode
- 74. Search a 2D Matrix
- 74. Search a 2D Matrix
- 74. Search a 2D Matrix
- [LeetCode]74. Search a 2D Matrix
- [LeetCode]74. Search a 2D Matrix
- 74. Search a 2D Matrix
- 74. Search a 2D Matrix
- leetcode 74. Search a 2D Matrix
- iOS汇编教程:ARM(1)和ARM(2)
- Mac 误删(抹掉)系统后,恢复重装
- if + WARN 可以简化code
- MYSQL无法打开的一些解决方法
- linux阻塞与非阻塞,同步与异步、I/O模型
- 74. Search a 2D Matrix
- linkedList模拟栈结构
- 灰度共生矩阵及相关特征值的计算——opencv
- Android强制设置横屏或竖屏
- STS创建Spring Boot项目实战(Rest接口、数据库、用户认证、分布式Token JWT、Redis操作、日志和统一异常处理)
- caffe-python接口图片分类demo
- UV扭曲
- React.js 官网资料摘记:State & 生命周期
- 集合嵌套之ArrayList嵌套ArrayList