LeetCode刷题笔记--74. Search a 2D Matrix

74. Search a 2D Matrix

Medium

79196FavoriteShare

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.

Example 1:

Input:
matrix = [
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]
target = 3
Output: true

Example 2:

Input:
matrix = [
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]
target = 13
Output: false

这道题虽然花了点时间写了两次二分法解决,但一次提交通过。

class Solution {
public:
    bool searchMatrix(vector>& matrix, int target) {
        if(matrix.size()==0)return false;
        if(matrix[0].size()==0)return false;
        int L=0;
        int R=matrix.size()-1;
        int mid;
        int r;
        while(L<=R)
        {
            mid=L+(R-L)/2;
            if(matrix[mid][0]==target)
            {
                return true;
            }
            else if(matrix[mid][0]>target)
            {
                R=mid-1;
            }
            else if(matrix[mid][0]             {
                if(matrix[mid][(matrix[0].size()-1)]                 else if(matrix[mid][(matrix[0].size()-1)]==target)return true;
                else if(matrix[mid][(matrix[0].size()-1)]>target){r=mid;break;}
            }
        }
        
        L=0;
        R=matrix[0].size()-1;
        while(L<=R)
        {
            mid=L+(R-L)/2;
            if(matrix[r][mid]==target)return true;
            else if(matrix[r][mid]>target)R=mid-1;
            else if(matrix[r][mid]         }
        
        return false;
    }
};

你可能感兴趣的:(LeetCode刷题笔记--74. Search a 2D Matrix)