My concise solution 12ms with O(m+n)


  • 0
    B

    class Solution {
    public:

    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        if(matrix.size() == 0)
        {
            return false;
        }
        
        int m = matrix.size();
        int n = matrix[0].size();
        
        int left = 0, right = m -1;
        while(left <= right)
        {
            int mid = left + (right - left) / 2;
            int value = matrix[mid][0];
            
            if(value == target)
            {
                return true;
            }
            else if(value > target)
            {
                right = mid - 1;
            }
            else
            {
                left = mid + 1;
            }
        }
        
        if(right < 0) return false; // target < matrix[0][0]
        
        int row = right; // Get the result row
        
        left = 0, right = n -1;
        while(left <= right)
        {
            int mid = left + (right - left) / 2;
            int value = matrix[row][mid];
            
            if(value == target)
            {
                return true;
            }
            else if(value > target)
            {
                right = mid - 1;
            }
            else
            {
                left = mid + 1;
            }
        }
        
        return false;
    }
    

    };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.