少数次过
1 class Solution { 2 public: 3 bool searchMatrix(vector<vector<int> > &matrix, int target) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 int m = matrix.size(); 7 int n = matrix[0].size(); 8 int left = 0; 9 int right = m-1; 10 int mid; 11 while (left <= right) { 12 mid = (left+right)/2; 13 if (target == matrix[mid][0]) return true; 14 if (target > matrix[mid][0]) left = mid+1; 15 else right = mid-1; 16 } 17 int row = (left+right)/2; 18 left = 0; 19 right = n-1; 20 while (left <= right) { 21 mid = (left+right)/2; 22 if (target == matrix[row][mid]) return true; 23 if (target > matrix[row][mid]) left = mid+1; 24 else right = mid-1; 25 } 26 return false; 27 } 28 };
C#
1 public class Solution { 2 public bool SearchMatrix(int[,] matrix, int target) { 3 int m = matrix.GetLength(0); 4 int n = matrix.GetLength(1); 5 int left = 0; 6 int right = m - 1; 7 int mid = 0; 8 while (left <= right) { 9 mid = (left + right) / 2; 10 if (target == matrix[mid, 0]) return true; 11 if (target > matrix[mid, 0]) left = mid + 1; 12 else right = mid - 1; 13 } 14 int row = (left + right) / 2; 15 left = 0; 16 right = n - 1; 17 while (left <= right) { 18 mid = (left + right) / 2; 19 if (target == matrix[row, mid]) return true; 20 if (target > matrix[row, mid]) left = mid + 1; 21 else right = mid - 1; 22 } 23 return false; 24 } 25 }