文章

每日LeetCode 151

2021.5.4 ・ 共 256 字,您可能需要 1 分钟阅读

Tags: LeetCode

编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值。该矩阵具有如下特性:

  • 每行中的整数从左到右按升序排列。

  • 每行的第一个整数大于前一行的最后一个整数。

    输入:matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
    输出:true
    
class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        int result = binarySearch(matrix, target);
        if (result == -1) {
            return false;
        } else {
            return binarySearch(matrix[result], target);
        }
    }

    public int binarySearch(int[][] matrix, int target) {
        int n = matrix.length;
        int left = -1;
        int right = n - 1;
        while (left < right) {
            int mid = left + (right - left + 1) / 2;
            if (matrix[mid][0] <= target) {
                left = mid;
            } else {
                right = mid - 1;
            }
        }
        return left;
    }

    public boolean binarySearch(int[] matrix, int target) {
        int n = matrix.length;
        int left = 0;
        int right = n - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (matrix[mid] == target) {
                return true;
            } else if (matrix[mid] < target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return false;
    }
}