74. Search a 2D Matrix
来源:互联网 发布:lca算法建模 编辑:程序博客网 时间:2024/06/07 05:27
问题描述
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 n = matrix.size(); if (n == 0) return false; int m = matrix[0].size(); if (m == 0) return false; int l = 0, r = m*n -1; while(l < r) { int mid = (l+r)/2; if (matrix[mid/m][mid%m] == target) return true; else if (matrix[mid/m][mid%m] > target) { r = mid - 1; } else { l = mid + 1; } } if (r == l) return matrix[r / m][r % m] == target; else return false; }};
注:这里要注意二分查找,经常会遇到不知道mid等于什么的情况,如果在循环外加一个r==l的判断就会不管mid = (l+r)/2 还是(l+r+1)/2还是(l+r-1)/2都可以
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
- [Leetcode] 22. Generate Parentheses
- GUI编程
- [LeetCode] 73. Set Matrix Zeroes
- 69.补间动画和属性动画
- Android 多媒体 通过MediaRecorder+SurfaceView实现拍照,录像
- 74. Search a 2D Matrix
- [学习交流] OC学习笔记之id类型及应用场景
- 网络编程
- gvim 操作
- [网易内推编程题] 地牢逃脱
- [LeetCode] 74. Search a 2D Matrix
- Android实现闹钟,通过AlarmManager+BroadcastReceiver(广播)
- PCA
- 学生选课抽签管理系统设计(一)