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
.
最简单的想法,转化成一维的,再用二分法:
1 class Solution { 2 public: 3 bool searchMatrix(vector<vector<int> > &matrix, int target) { 4 5 int row=matrix.size(); 6 int col=matrix[0].size(); 7 vector<int> m(row*col); 8 9 for(int i=0;i<row;i++) 10 { 11 for(int j=0;j<col;j++) 12 { 13 m[i*col+j]=matrix[i][j]; 14 } 15 } 16 17 int left=0; 18 int right=m.size()-1; 19 int mid; 20 while(left<=right) 21 { 22 mid=(left+right)/2; 23 if(m[mid]>target) 24 right=mid-1; 25 else if(m[mid]<target) 26 left=mid+1; 27 else 28 return true; 29 } 30 return false; 31 32 } 33 };
第二种思路,直接使用二分法
把一维数字转化为二维的坐标的方法:
第n个元素,在n/col行,n%col列
1 class Solution { 2 public: 3 bool searchMatrix(vector<vector<int> > &matrix, int target) { 4 5 int row=matrix.size(); 6 int col=matrix[0].size(); 7 8 int left=0; 9 int right=row*col-1; 10 int mid; 11 int m; 12 while(left<=right) 13 { 14 mid=(left+right)/2; 15 m=matrix[mid/col][mid%col]; 16 if(m>target) 17 right=mid-1; 18 else if(m<target) 19 left=mid+1; 20 else 21 return true; 22 } 23 return false; 24 } 25 };