代码改变世界

leetcode - Search a 2D Matrix

2013-10-27 15:08  张汉生  阅读(134)  评论(0编辑  收藏  举报

 

 1 class Solution {
 2 public:
 3     bool searchMatrix(vector<vector<int> > &matrix, int target) {
 4         // IMPORTANT: Please reset any member data you declared, as
 5         // the same Solution instance will be reused for each test case.
 6         int m =matrix.size();
 7         if (m<=0)
 8             return false;
 9         int n = matrix[0].size();
10         if (n<=0)
11             return false;
12         int left=0, right=m-1, mid;
13         while(left<=right){
14             mid = (left+right)/2;
15             if (matrix[mid][0]<=target && matrix[mid][n-1]>=target)
16                 break;
17             if (matrix[mid][0]>target)
18                 right=mid-1;
19             if (matrix[mid][n-1]<target)
20                 left = mid+1;
21         }
22         vector<int> row = matrix[mid];
23         if (row[0]>target || row[n-1]<target)
24             return false;
25         left = 0, right = n-1;
26         while (left<=right){
27             mid = (left+right)/2;
28             if (row[mid]==target)
29                 return true;
30             if(row[mid]>target)
31                 right = mid-1;
32             else left = mid+1;
33         }
34         return false;
35     }
36 };