LeetCode-Search a 2D Matrix II

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_24133491/article/details/87883009

Description:
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 in ascending from left to right.
  • Integers in each column are sorted in ascending from top to bottom.

Example:
Consider the following matrix:

[
  [1,   4,  7, 11, 15],
  [2,   5,  8, 12, 19],
  [3,   6,  9, 16, 22],
  [10, 13, 14, 17, 24],
  [18, 21, 23, 26, 30]
]

Given target = 5, return true.
Given target = 20, return false.

题意:给定一个二维数组matrix和一个目标元素target,计算在二维数组中是否存在元素target;其中,数组matrix每一行都是有序的;

解法:虽然数组matrix中的每一行都是有序的,但是与Search a 2D matrix不同的是,不满足每行的首个元素比前一行的最后一个元素大;不过对于每一行还是有序的,所以,我们可以利用分治算法,对每一行利用二分查找;

Java
class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return false;
        }
        return search(matrix, 0, matrix.length - 1, target);
    }
    
    private boolean search(int[][] matrix, int topRow, int bottomRow, int target) {
        if (topRow == bottomRow) {
            return binarySearch(matrix[topRow], target);
        }
        int mid = (topRow + bottomRow) / 2;
        return search(matrix, topRow, mid, target) || 
            search(matrix, mid + 1, bottomRow, target);
    }
    
    private boolean binarySearch(int[] matrix, int target) {
        int low = 0;
        int high = matrix.length - 1;
        while (low <= high) {
            int mid = (low + high) / 2;
            if (matrix[mid] == target) {
                return true;
            } else if (matrix[mid] > target) {
                high = mid - 1;
            } else {
                low = mid + 1;
            }
        }
        return false;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_24133491/article/details/87883009