74. Search a 2D Matrix

来源:互联网 发布:淘宝上传宝贝失败 编辑:程序博客网 时间:2024/06/03 19:50

Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:

  • Integers in each row are sorted from left to right.
  • The first integer of each row is greater than the last integer of the previous row.

For example,

Consider the following matrix:

[  [1,   3,  5,  7],  [10, 11, 16, 20],  [23, 30, 34, 50]]
Given target = 3, return true.

这道题思路比较简单,就是二分查找,首先确定范围,然后针对具体的一行进行二分查找就可以啦,代码如下:

public boolean searchMatrix(int[][] matrix, int target) {
        boolean flag = false;
        // 特殊情况处理
        if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
            return false;
        }
        
        // 找到target所在的行
        int row = matrix.length;
        int col = matrix[0].length;
        for(int i = 0; i < row; i++){
            if(target <= matrix[i][col - 1]){
                flag = binarySearch(i, matrix, target);
                break;
            }
        }
        
        return flag;
    }
    
    private boolean binarySearch(int row, int[][] matrix, int target){
        int left = 0, right = matrix[0].length - 1;
        while(left < right){
            int mid = (left + right) / 2;
            if(matrix[row][mid] == target){
                return true;
            }else if(matrix[row][mid] < target){
                left = mid + 1;
            }else{
                right = mid - 1;
            }
        }
        
        if(matrix[row][left] == target){
            return true;
        }else{
            return false;
        }
    }

0 0