74. Search a 2D Matrix
来源:互联网 发布:java boolean 异或 编辑:程序博客网 时间:2024/05/17 22:46
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.
第一种方法:先对第一列用二分法,求出target在哪一列,然后再在列里面用二分法。
class Solution {public: bool searchMatrix(vector<vector<int> >& matrix, int target) { int m=matrix.size(); int n=matrix[0].size(); if(target<matrix[0][0]||target>matrix[m-1][n-1]) return false; else if(target>=matrix[m-1][0]&&target<=matrix[m-1][n-1]) return BinarySearch(matrix,target,m-1,0,n-1); else { int low=0,high=m-1; while(high-low>1) { int mid=(high+low)/2; if(target==matrix[mid][0]) return true; else if(target>matrix[mid][0]) low=mid; else high=mid; } return BinarySearch(matrix,target,low,0,n-1); } } bool BinarySearch(vector<vector<int> >& matrix,int target,int row,int left,int right) { int mid; while(left<right) { mid=(left+right)/2; if(target==matrix[row][mid]) return true; else if(target<matrix[row][mid]) right=mid-1; else left=mid+1; } return target==matrix[row][left]; }};
第二种方法:不要把它看作二维矩阵,把它看成连续的一维数组,再使用二分法,感觉简单很多。
class Solution {public: bool searchMatrix(vector<vector<int> >& matrix, int target) { int m=matrix.size(); int n=matrix[0].size(); int low=0; int high=m*n-1; while(low<=high) { int mid=(low+high)/2; if(matrix[mid/n][mid%n]==target) return true; else if(matrix[mid/n][mid%n]>target) high=mid-1; else low=mid+1; } 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
- 上两道js面试题,关于数组字符串 之间的转化
- hash_table
- 工作流系统之三十四 集成用户系统
- mysql导入文件出现Data truncated for column 'xxx' at row 1的原因
- 网络与系统学习路线
- 74. Search a 2D Matrix
- 工作流系统之三十五 自由流的实现
- java实现租车系统
- LA 3177 Beijing Guards 二分 -
- 工作流系统之三十六 工作流软件中的那些人
- OpenCL异构并行计算编程笔记(2):命令队列与内存对象
- 数据文件坏块处理
- 工作流系统之三十七 自由流的实现(续)
- C struct 成员冒号