Search a 2D Matrix
来源:互联网 发布:淘宝上的老兵户外军品 编辑:程序博客网 时间:2024/06/18 17:12
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
.
class Solution {public: bool searchMatrix(vector<vector<int> > &matrix, int target) { int size = matrix.size(); if (size < 1) { return false; } int left = 0; int right = size - 1; while (left < right-1) { int mid = left + (right-left)/2; if (matrix[mid][0] == target) { return true; } else if (matrix[mid][0] > target) { right = mid - 1; } else { left = mid; } } if (matrix[left][0] == target || matrix[right][0] == target) { return true; } int row = left; if (left != right) { if (matrix[right][0] < target) { row = right; } } left = 0; right = matrix[row].size() - 1; while (left <= right) { int mid = left + (right-left)/2; if (matrix[row][mid] == target) { return true; } else if (matrix[row][mid] > target) { right = mid - 1; } else { left = 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
- [授权发表]源码分析:动态分析 C 程序函数调用关系
- 一个C++解析HTML的库
- Java——面向对象
- 右侧导航条
- [黑马程序员]04[c语言]递归算法的妙用, 捕鱼量算法问题
- Search a 2D Matrix
- MR table
- VC获取屏幕分辨率及大小相关
- [黑马程序员]05[c 语言]常见排序算法的时间复杂度比较
- 最完整PHP.INI中文版
- 关于.SO的破解
- 2015年04月14日学习
- POJ 2195 解题报告
- leetcode难度及面试频率