Search a 2D Matrix--LeetCode

落日映苍穹つ 2022-08-07 11:44 136阅读 0赞

题目:

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. [
  2. [1, 3, 5, 7],
  3. [10, 11, 16, 20],
  4. [23, 30, 34, 50]
  5. ]

Given target = 3, return true.

思路:先从行找到合适的位置,使用二分查找,再在这一行查找目标值,也是二分查找,时间复杂度为O(lgm + lgn)

  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. using namespace std;
  5. /*
  6. 在一个二维数组中查找一个元素 只不过这个数组是有特殊排序的
  7. 使用二分查找
  8. */
  9. bool Search2DMatrix(vector<vector<int> >& vec,int key)
  10. {
  11. int pos;
  12. int low,high,mid;
  13. low = 0;
  14. high = vec.size()-1;
  15. while(low<=high)
  16. {
  17. mid = low+(high-low)/2;
  18. if(vec[mid][0] == key)
  19. return true;
  20. else if(vec[mid][0] < key)
  21. low= mid+1;
  22. else
  23. high = mid-1;
  24. }
  25. pos = low; //这一块相当于使用STL中的lower_bound函数,找下界
  26. low = 0;
  27. high = vec[0].size()-1;
  28. while(low<=high)
  29. {
  30. mid = low+(high-low)/2;
  31. if(vec[pos][mid] == key)
  32. return true;
  33. else if(vec[pos][mid]>key)
  34. high = mid-1;
  35. else
  36. low = mid+1;
  37. }
  38. return false;
  39. }
  40. int main()
  41. {
  42. vector<vector<int> > vec;
  43. int array[]={1,3,5,7};
  44. int array1[]={10,11,16,20};
  45. int array2[]={23,30,34,50};
  46. vector<int> vec1(array,array+sizeof(array)/sizeof(int));
  47. vec.push_back(vec1);
  48. vector<int> vec2(array1,array1+sizeof(array1)/sizeof(int));
  49. vec.push_back(vec2);
  50. vector<int> vec3(array2,array2+sizeof(array2)/sizeof(int));
  51. vec.push_back(vec3);
  52. cout<<Search2DMatrix(vec,300);
  53. return 0;
  54. }

发表评论

表情:
评论列表 (有 0 条评论,136人围观)

还没有评论,来说两句吧...

相关阅读