My binary search cpp solution


  • -1
    C
    class Solution {
    public:
        bool searchMatrix(vector<vector<int>>& matrix, int target) 
        {
            int dim = matrix.size();
            
            int start = 0, end = dim;
            while(end - start > 1)
            {
                int mid = start + (end - start) / 2;
                
                if(target > matrix[mid][0])
                    start = mid;
                else if(target < matrix[mid][0])
                    end = mid;
                else
                    return true;
            }
            
            int row = start;
            start = 0, end = matrix[0].size();
            while(end - start > 1)
            {
                int mid = start + (end - start) / 2;
                
                if(target > matrix[row][mid])
                    start = mid;
                else if(target < matrix[row][mid])
                    end = mid;
                else
                    return true;
            }
            
            return target == matrix[row][start];
        }
    };

Log in to reply
 

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