my very easy understand java solution


  • 0
    L
    public boolean searchMatrix(int[][] matrix, int target) {
        if(matrix == null || matrix.length == 0) return false;
        int m = matrix.length, n = matrix[0].length;
        if(matrix[0][0] > target || target > matrix[m-1][n-1]) return false;
        int[] nums = null;
        for(int i = 0; i < m; i++){
           //find the row the target may be in ,then binary search it
            if(matrix[i][n-1] >= target && target >= matrix[i][0] ){
                nums = matrix[i];
                if(binarySearch(nums,target)){
                    return true;
                }
            }
        }
        return false;
    }
    
    private boolean binarySearch(int[]nums,int target){
        int start = 0,mid = 0, end = nums.length - 1;
        while(start <= end){
            mid = start + (end - start) / 2;
            if(nums[mid] == target){
                return true;
            }else if(nums[mid] < target){
                start = mid + 1;
            }else{
                end = mid - 1;
            }
        }
        return false;
    }

Log in to reply
 

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