leetcode 240. Search a 2D Matrix II

冷不防 2022-08-20 14:07 206阅读 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 in ascending from left to right.
Integers in each column are sorted in ascending from top to bottom.
For example,

Consider the following matrix:

[
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
]
Given target = 5, return true.

Given target = 20, return false.

  1. class Solution {
  2. public:
  3. bool searchMatrix(vector<vector<int>>& matrix, int target) {
  4. if(matrix.empty())
  5. return false;
  6. if(matrix[0].empty())
  7. return false;
  8. if(matrix[0][0]>target||matrix[matrix.size()-1][matrix[0].size()-1]<target)
  9. return false;
  10. int curX=0,curY=0;
  11. bool horizontal=true;
  12. while(curX!=matrix[0].size()&&curY!=matrix.size())
  13. {
  14. if(horizontal)
  15. {
  16. while(curX!=matrix[0].size()&&matrix[curY][curX]<target)
  17. curX++;
  18. if(curX==matrix[0].size()||matrix[curY][curX]>target)
  19. {
  20. curX--;
  21. horizontal=false;
  22. curY++;
  23. }
  24. else
  25. return true;
  26. }
  27. else
  28. {
  29. while(curY!=matrix.size()&&matrix[curY][curX]<target)
  30. curY++;
  31. if(curY==matrix.size()||matrix[curY][curX]>target)
  32. {
  33. if(curY==matrix.size()&&matrix[curY-1][curX]<target)
  34. return false;
  35. curY--;
  36. horizontal=false;
  37. curX--;
  38. }
  39. else
  40. return true;
  41. }
  42. }
  43. return false;
  44. }
  45. };

accepted

发表评论

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

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

相关阅读