[LeetCode]Search a 2D Matrix
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<vector<int>>& 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]<target) 12 { 13 left = mid+1; 14 } 15 else 16 { 17 right = mid-1; 18 } 19 } 20 int pos = right; 21 if(pos<0) return false; 22 left=0; 23 right = n-1; 24 while(left<=right) 25 { 26 int mid = (left+right)/2; 27 if(matrix[pos][mid]==target) return true; 28 else if(matrix[pos][mid]<target) 29 { 30 left = mid+1; 31 } 32 else 33 { 34 right = mid-1; 35 } 36 } 37 return false; 38 } 39 };
这题也可以从右上角遍历,时间复杂度O(m)+O(n)。
1 class Solution { 2 public: 3 bool searchMatrix(vector<vector<int>>& 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<m && col>=0) 8 { 9 if(matrix[row][col]==target) return true; 10 else if(matrix[row][col]<target) row++; 11 else col--; 12 } 13 return false; 14 } 15 };