【二分查找】Leetcode 74. 搜索二维矩阵【中等】

搜索二维矩阵

给你一个满足下述两条属性的 m x n 整数矩阵:

  • 每行中的整数从左到右按非严格递增顺序排列。
  • 每行的第一个整数大于前一行的最后一个整数。

给你一个整数 target ,如果 target 在矩阵中,返回 true ;否则,返回 false 。

示例 1:
【二分查找】Leetcode 74. 搜索二维矩阵【中等】_第1张图片
输入:matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
输出:true

解题思路1

  • 1、从矩阵的右上角开始查找。
  • 2、如果当前元素等于目标值,则返回true。
  • 3、如果当前元素大于目标值,则说明目标值在当前元素的左侧列,列索引减1。
  • 4、如果当前元素小于目标值,则说明目标值在当前元素的下方行,行索引加1。
  • 5、重复步骤2-4,直到找到目标值或者超出矩阵边界。

Java实现1

public class SearchMatrix {
   

    public boolean searchMatrix(int[][] matrix, int target) {
   
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
   
            return false;
        }

        int rows = matrix.length;
        int cols = matrix[0].length;
        int row = 0;
        int col = cols - 1;

        while (row < rows && col >= 0) {
   
            if (matrix[row]

你可能感兴趣的:(算法,leetcode,矩阵,算法)