Search a 2D Matrix
来源:互联网 发布:公司注销,淘宝企业店铺 编辑:程序博客网 时间:2024/06/04 01:23
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
.
Solution:
class Solution {public: bool searchMatrix(vector<vector<int> > &matrix, int target) { int m = matrix.size(); int n = matrix[0].size(); int left = 0, right = m - 1; while(left <= right) { int mid = (left + right) / 2; if(target == matrix[mid][0]) return true; else if(target > matrix[mid][0]) left = mid + 1; else right = mid - 1; } int row = max(right, 0); left = 0; right = n - 1; while(left <= right) { int mid = (left + right) / 2; if(target == matrix[row][mid]) return true; else if(target > matrix[row][mid]) left = mid + 1; else right = mid - 1; } return false; }};
0 0
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D matrix
- Search a 2D matrix
- LeetCode OJ Sum Root to Leaf Numbers
- LeetCode OJ Longest Palindromic Substring
- tju 4072. 3D Birds-Shooting Game(k-d树)
- 物理渲染-基于物理的光照模型
- Hdoj 1179 Ollivanders: Makers of Fine Wands since 382 BC. 【二分匹配】
- Search a 2D Matrix
- 浅谈 -128的原码 反码 补码
- 顺序容器:容器的赋值、swap、assign
- boost::mutex vs boost::recursive_mutex
- 从java一道多线程题目想到
- 我终于变成了一个喜欢自己的姑娘(有效地改变自己)
- C语言 a++为什么不能作为左值?
- DataSet、DataTable、DataRow、DataColumn区别及使用实例
- 2015-第3周项目4-考了语文数学的学生