CSharp Binary Search Solution


  • 0
    V

    Loop over the matrix rows to find the possible target row and then it does binary search.

    public class Solution {
        public bool SearchMatrix(int[,] matrix, int target) {
            int rows = matrix.GetLength(0);
            int cols = matrix.GetLength(1) - 1;
            int currRow = 0;
            
            // Find the target row
            for (int i = 0; i < rows; i++)
            {
                if(target == matrix[i, cols]){
                  return true;  // Quick win
                } 
                else if (target < matrix[i, cols])
                {
                    currRow = i;
                    break;
                }
            }
            
            int lo = 0;
            int hi = cols;
            while(lo<=hi){
                int m = lo + (hi -lo)/2;
                if(matrix[currRow, m] == target) return true;
                if(matrix[currRow, m] < target) lo = m + 1;
                if(matrix[currRow, m] > target) hi = m - 1;
            }
            return false;
        }
    }
    

Log in to reply
 

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