LeetCode 74. Search a 2D Matrix
来源:互联网 发布:深圳市宜众软件怎么样 编辑:程序博客网 时间:2024/05/17 02:38
题目
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.
分析
这是一道二分查找题, 只不过扩展到了二维. 需要注意循环判定条件以及对于lo
和hi
的修改. 这里我们对这两个变量起了不同的名字.
外层循环寻找target
可能位于哪一行, 而内层循环确定target
是否存在.与我在这篇文章中介绍的题目类似, up
为可能的行的最小下标, down
为可能的行的最大下标加1. 如果target
位于middle
行两端数字构成的闭区间内, 则在此行内进行二分查找, 查找的结果即为函数返回值.
解答
class Solution {public: bool searchMatrix(vector<vector<int>>& matrix, int target) { int m = matrix.size(); if (m) { int n = matrix[0].size(); if (n) { int up = 0, down = m; while (up < down) { int middle = up + (down-up) / 2; if (matrix[middle][0] <= target && target <= matrix[middle][n-1]) { int left = 0, right = n; while (left < right) { int mid = left + (right-left) / 2; if (matrix[middle][mid] == target) { return true; } else if (matrix[middle][mid] > target) { right = mid; } else { left = mid + 1; } } return false; } else if (matrix[middle][n-1] < target) { up = middle+1; } else if (matrix[middle][0] > target){ down = middle; } } return false; } return false; } 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
- Leetcode 74. Search a 2D Matrix
- [LeetCode]74. Search a 2D Matrix
- 74. Search a 2D Matrix LeetCode
- [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
- 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
- 静态方法中不能new内部类的实例对象的总结
- 购物车-----ListView 中CheckBox混乱
- 道路交通事故处理程序规定
- 快速排序和冒泡排序的时间复杂度分析(C++算法实现对比)
- Spark如何使用Akka实现进程、节点通信的简明介绍
- LeetCode 74. Search a 2D Matrix
- leetcode_084 Largest Rectangle in Histogram
- ML实验-KNN(续)
- memset是core dump高发区
- Android自定义控件系列八:详解onMeasure()(二)--利用onMeasure测量来实现图片拉伸永不变形,解决屏幕适配问题
- 进程与线程的区别
- CentOS 6.6系统安装一些软件
- 有序表的最小和
- Linux内核源码下载地址