Search a 2D Matrix
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
.
二分查找,时间复杂度O(logm)+O(logn)。
1 class Solution { 2 public: 3 bool searchMatrix(vector>& matrix, int target) { 4 if(matrix.size()==0 || matrix[0].size()==0) return false; 5 int m=matrix.size(),n=matrix[0].size(); 6 int left=0,right=m-1; 7 while(left<=right) 8 { 9 int mid = (left+right)/2;10 if(matrix[mid][0]==target) return true;11 else if(matrix[mid][0]
这题也可以从右上角遍历,时间复杂度O(m)+O(n)。
1 class Solution { 2 public: 3 bool searchMatrix(vector>& matrix, int target) { 4 if(matrix.size()==0 || matrix[0].size()==0) return false; 5 int m=matrix.size(),n=matrix[0].size(); 6 int row=0,col=n-1; 7 while(row =0) 8 { 9 if(matrix[row][col]==target) return true;10 else if(matrix[row][col]