240. Search a 2D Matrix II
来源:互联网 发布:javaweb js 跨域 编辑:程序博客网 时间:2024/06/04 23:20
240. Search a 2D Matrix II
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 in ascending from left to right.
- Integers in each column are sorted in ascending from top to bottom.
For example,
Consider the following matrix:
[ [1, 4, 7, 11, 15], [2, 5, 8, 12, 19], [3, 6, 9, 16, 22], [10, 13, 14, 17, 24], [18, 21, 23, 26, 30]]
Given target = 5, return true.
Given target = 20, return false.
分析:
首先看到题目的设定,是行和列分别降序,那么最自然的想法就是,我先在行找,如果找到一个值,它的前一个值比pivot小,后一个值比pivot大,那么再从这一列往下找,如果找到了比该值大的值还没找到,则断定没有这个值。
但是这样的做法是时间复杂度是O(n+m),因此,对于这种有序数组中查找数的题目,我们很自然可以想到用二分法查找,用二分法代替上面的逐个查找,那么复杂的就能降到O(mlogn)。
#include <iostream>#include <vector>using namespace std;class Solution {public: bool searchMatrix(vector<vector<int>>& matrix, int target) { if (matrix.empty() || matrix.size() < 1 || matrix[0].size() < 1) { return false; } return searchRecCol(matrix, target, 0, matrix.size() - 1); } bool searchRecCol(vector<vector<int>>& matrix, int target, int top, int bottom) { if (top > bottom) return false; int mid = top + (bottom - top) / 2; if (matrix[mid].front() <= target && target <= matrix[mid].back()) if (searchRow(matrix[mid], target)) return true; if (searchRecCol(matrix, target, top, mid - 1)) return true; if (searchRecCol(matrix, target, mid + 1, bottom)) return true; return false; } bool searchRow(vector<int>& vector, int target) { int left = 0, right = vector.size() - 1; while (left <= right) { int mid = left + (right - left) / 2; if (vector[mid] == target) return true; if (vector[mid] < target) left = mid + 1; else right = mid - 1; } return false; }};
阅读全文
0 0
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240. Search a 2D Matrix II
- 240.Search a 2D Matrix II
- bzoj 1053 反素数
- 腾讯-算法工程师电话面试
- resource fork, Finder information, or similar detritus not al site:forums.developer.apple.com..
- 项目管理和构建】十分钟教程,eclipse配置maven + 创建maven项目
- 【bzoj 2456】mode(乱搞)
- 240. Search a 2D Matrix II
- Oracle sql性能优化1
- 4.2_控制流2while__range语句.docx
- [Git] Git初应用
- 使用visual studio 2017 创建动态链接库(DLL),供VB6.0使用
- 自由幻想UI之信息显示
- utunbu安装中文输入法(转载)
- [Oracle]理解undo表空间
- 4.3_控制流3break_continue__pass.docx