74. Search a 2D Matrix
来源:互联网 发布:网络语飙车是什么意思 编辑:程序博客网 时间:2024/05/21 11:05
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) { if (matrix.empty() || matrix[0].empty()) return false; if (target < matrix[0][0]) return false; int row = matrix.size(), col = matrix[0].size(); int r = 0; for (int i = 0; i < row - 1; i++) { if (matrix[i][0] <= target && matrix[i+1][0] > target) { r = i; break; } } if (target >= matrix[row-1][0]) r = row - 1; int begin = 0, end = col - 1; int mid = (begin + end) / 2; while (begin <= end) { if (target == matrix[r][mid]) return true; if (target < matrix[r][mid]) end = mid - 1; else if (target > matrix[r][mid]) begin = mid + 1; mid = (begin + end) / 2; } 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
- 二叉树的创建以及各种遍历
- ixchariot(网络测试工具)v7.3 免费版下载附使用教程
- 重识java2
- 数据结构--单链表实现
- 责任链模式浅析
- 74. Search a 2D Matrix
- datetimepicker使用时样式错位的解决
- HDOJ 2025 查找最大元素 查找最大字母
- matlab练习程序(生成多维高斯分布概率密度函数)
- Linux学习之CentOS(十三)--CentOS6.4下Mysql数据库的安装与配置
- [jzoj]3578. 【CEOI2013】Adriatic(记忆化/DP)
- struts2 验证码详情
- [Leetcode] 530. Minimum Absolute Difference in BST 解题报告
- 22. 向上造型