矩阵二分法查找 —— z字形查找

219 阅读1分钟

240. Search a 2D Matrix II
Write an efficient algorithm that searches for a value target in an m x n integer matrix 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 1:

Input: 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]], target = 5
Output: true

Example 2:

Input: 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]], target = 20
Output: false

z字形查找,从matrix[0][n-1]开始,如果target > 当前的值,因为当前的值所在的行都是比当前值小的,所以x++。 如果target < 当前的值,因为当前值所在列都是比x大的,所以y--;

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

        int x = 0;
        int y = n-1;
        while(x < m && y >= 0) {
            int num = matrix[x][y];
            if(num == target) {
                return true;
            } else if(num > target) {
                y--;
            } else {
                x++;
            }
        }
        return false;
    }
}