4. 二维数组中的查找

剑指 Offer 04. 二维数组中的查找

在一个 n * m 的二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个高效的函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。

示例:
现有矩阵 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,返回 true

给定 target = 20,返回 false

限制:

0 < = n < = 1000 0 <= n <= 1000 0<=n<=1000

0 < = m < = 1000 0 <= m <= 1000 0<=m<=1000

注意:本题与主站 240 题相同:https://leetcode-cn.com/problems/search-a-2d-matrix-ii/

解题思路

因为右上角的数字,是当前列的最小值,当前行的最大值,所以可以用变相的二分思想

  • 从右上角开始,首先选中右上角的数字,如果该数字等于要查找的数字,则查找过程结束。
  • 如果该数字大于target,则剔除该数字所在的列,因为这一列中的数字都会大于target
  • 如果该数字小于target则剔除该数字所在的行,因为这一行中的数字都会小于target

Java代码

class Solution {
    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][col] == target){
                return true;
            }else if(matrix[row][col] > target){
                col--;//把查找范围剔除该列
            }else{
                row++;//把查找范围剔除该行
            }
        }
        return false;//矩阵遍历结束都没有找到,返回false
    }
}

go代码

func findNumberIn2DArray(matrix [][]int, target int) bool {
    if matrix == nil || len(matrix) == 0 {return false}
    
    row,col := len(matrix),len(matrix[0])
    for i,j := 0,col -1;i < row && j >= 0; {
        if matrix[i][j] == target {
            return true
        }else if matrix[i][j] < target{
            i++
        }else{
            j--
        }
    }
    return false
}

在这里插入图片描述

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值