LeetCode 240. 搜索二维矩阵 II

传送门

Solution

思路1:

暴力搜索

class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        for (int[] row: matrix) {
            for (int x : row) {
                if (x == target) 
                    return true;
            }
        }
        return false;
    }
}

思路2:

每行有序,可以二分查找

class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        for (int[] row: matrix) {
            if (searchVal(row, target)) return true;
        }
        return false;
    }

    public boolean searchVal(int[] row, int target) {
        int l = 0, r = row.length - 1;
        while (l <= r) {
            int mid = (r - l) / 2 + l;
            if (row[mid] == target) return true;
            if (row[mid] < target) l = l + 1;
            else r = r - 1;
        }
        return false;
    }
}

思路3:

根据矩阵特性,从右上角往左下角搜索,右上角\((x,y)\)\(target\)对比,

  • 如果\((x,y)>target\),因为每一列从上往下递增,所以该列没必要往下 ,则y--
  • 如果\((x,y)<target\),因为每一行从左到右递增,所以该行没必要往左 ,则x++
class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        int n = matrix.length, m = matrix[0].length;
        int x = 0, y = m - 1;
        while (x < n && y > -1) {
            if (matrix[x][y] == target) return true;
            if (matrix[x][y] > target) y -= 1;
            else x += 1;
        }
        return false;
    }
}

//  (0, m-1)  (n, 0)
posted @ 2021-10-26 23:02  Frontierone  阅读(30)  评论(0编辑  收藏  举报