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]
]

思想:两次二分查找
  1. bool searchMatrix(vector<vector<int> > &matrix, int target) {
  2. int row=matrix.size();
  3. if(row==0) return false;
  4. int col=matrix[0].size();
  5. if(col==0) return false;
  6. int low=0;
  7. int end=row-1;
  8. int line=-1;
  9. bool flag=false;
  10. int mid=0;
  11. while(low<=end) {
  12. mid=low+(end-low)/2;
  13. if(target==matrix[mid][0]) {
  14. line=mid;
  15. flag=true;
  16. break;
  17. }
  18. if(target<matrix[mid][0]) {
  19. end=mid-1;
  20. } else {
  21. low=mid+1;
  22. }
  23. }
  24. if(flag) {
  25. return true;
  26. } else {
  27. line=end;
  28. }
  29. if(line<0) return false;
  30. //if(line==row) line=row-1;
  31. low=0;
  32. end=col-1;
  33. while(low<=end) {
  34. mid=low+(end-low)/2;
  35. if(target==matrix[line][mid]) {
  36. //line=mid;
  37. return true;
  38. }
  39. if(target<matrix[line][mid]) {
  40. end=mid-1;
  41. } else {
  42. low=mid+1;
  43. }
  44. }
  45. return false;
  46. }
posted @ 2014-08-10 21:57  purejade  阅读(94)  评论(0)    收藏  举报