Java LeetCOde 74. Search two-dimensional matrix

Write an efficient algorithm to determine whether there is a target value in the mxn matrix. The matrix has the following characteristics:
the integers in each row are arranged in ascending order from left to right.
The first integer in each line is greater than the last integer in the previous line.

Insert picture description here

class Solution {
    
    
    public boolean searchMatrix(int[][] matrix, int target) {
    
    
        int m = matrix.length;
        if(m==0){
    
    
            return false;
        }
        int n = matrix[0].length;

        int left=0;
        int right=m*n-1;
        int mid=0;
        while(left<=right){
    
    
            mid = (left+right)/2;
            int row = mid/n;
            int col = mid%n;
            if(matrix[row][col]==target){
    
    
                return true;
            }
            if(matrix[row][col]<target){
    
    
                left=mid+1;
            }else {
    
    
                right=mid-1;
            }
        }
        return false;
    }
}

Guess you like

Origin blog.csdn.net/sakura_wmh/article/details/111148144