【面试题】二维数组中的查找(Java、Python实现)

题目描述

在这里插入图片描述

解法一:暴力法

时间复杂度:O(n*m),二维数组中的每个元素都被遍历一次,因此时间复杂度为二维数组的大小。
空间复杂度:O(1)

Python

class Solution(object):
    def findNumberIn2DArray(self, matrix, target):
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """
        if not matrix or len(matrix) == 0 or len(matrix[0]) == 0:
            return False
        for i in range(len(matrix)):
            for j in range(len(matrix[0])):
                if matrix[i][j] == target:
                    return True
        return False

Java

class Solution {
    public boolean findNumberIn2DArray(int[][] matrix, int target) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0)
            return false;
        for (int i=0; i< matrix.length; i++){
            for (int j=0; j< matrix[i].length; j++){
                if (matrix[i][j] == target)
                    return true;
            }
        }
        return false;
    }
}

解法二:线性查找法

由于给定的二维数组具备每行从左到右递增以及每列从上到下递增的特点,当访问到一个元素时,可以排除数组中的部分元素。

比如,每⼀次都是选取数组查找范围内的右上角数字,
(1)如果该数字等于要查找的数字, 查找过程结束;
(2)如果该数字大于要查找的数字, 剔除这个数字所在的列(因为该数字已经是该列的最小元素了);
(3)如果该数字小于要查找的数字, 剔除这个数字所在的行(因为该数字已经是该行的最大元素了)。

时间复杂度:O(n+m),最多访问 n行和 m列,因此循环体最多执行 n + m 次。
空间复杂度:O(1)

Python

class Solution(object):
    def findNumberIn2DArray(self, matrix, target):
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """
        if not matrix or len(matrix) == 0 or len(matrix[0]) == 0:
            return False
        # 从右上角的数字开始查找
        row = 0
        col = len(matrix[0]) -1
        while row < len(matrix) and col >= 0:
            if matrix[row][col] == target:
                return True
            if matrix[row][col] > target: # 当前位置上的数大于目标,应该往左边继续找
                col -= 1
            if matrix[row][col] <target: # 当前位置上的数小于目标,应该往下边继续找
                row += 1
        return False

Java

class Solution {
    public boolean findNumberIn2DArray(int[][] matrix, int target) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0)
            return false;
        // 从右上角开始查找
        int row = 0;
        int col = matrix[0].length -1;
        while (row < matrix.length && col >=0){
            if (matrix[row][col] > target)
                col -= 1;
            else if (matrix[row][col] < target)
                row += 1;
            else // 当前位置上的数等于目标
                return true;
        }
        return false;
    }
}

同样地,我们也可以选择,从左下角的数字开始查找

Python

class Solution(object):
    def findNumberIn2DArray(self, matrix, target):
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """
        if not matrix or len(matrix) ==0 or len(matrix[0]) ==0:
            return False
        # 从左下角的数字开始查找
        row = len(matrix)-1
        col = 0
        while row >= 0 and col < len(matrix[0]):
            if matrix[row][col] > target: # 如果当前位置上的数大于目标,应该往上边继续找
                row -= 1
            elif matrix[row][col] < target: # 如果当前位置上的数小于目标,应该往右边继续找
                col += 1
            else: # 当前位置上的数等于目标
                return True
        return False

Java

class Solution {
    public boolean findNumberIn2DArray(int[][] matrix, int target) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0)
            return false;
        // 从左下角开始查找
        int row = matrix.length -1;
        int col = 0;
        while (row >=0 && col < matrix[0].length){
            if (matrix[row][col] > target)
                row -= 1;
            else if (matrix[row][col] < target)
                col += 1;
            else
                return true;
        }
        return false;
    }
}

参考

https://leetcode-cn.com/problems/er-wei-shu-zu-zhong-de-cha-zhao-lcof/solution/mian-shi-ti-04-er-wei-shu-zu-zhong-de-cha-zhao-zuo/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值