在一个二维数组中查找整数【python实现】

导读:本篇文章讲解 在一个二维数组中查找整数【python实现】,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

在一个二维数组中查找整数【刷题记录】

1、题目描述:

在这里插入图片描述

2、思路:

题目类似二分排序,但注意:数组本身的规律,按照二分排序比大小选择目标的规律,可以从左下角开始,如果array[i][j]大于target则往上移动,小于则往右移动,需要注意不能越界。因此就是找规律二分排序!

3、代码示例

# -*- coding:utf-8 -*-
class Solution:
    # array 二维列表
    def Find(self, target, array): #获得数组的列数和行数
        # write code here
        row = len(array)-1    ##行数
        col = len(array[0])-1  ##列数
        i = row
        j = 0
        while j<=col and i>=0: ##从左下角开始查找
            if target < array[i][j]:
                i -=1  #往上移动
            elif target > array[i][j]:
                j += 1  #往右移动
            else:
                return True  #返回标记True
        return False     #返回标记False 
        
if __name__ == "__main__":
    array1 = [[1,2],[2,4],[5,6],[7,9]]  #测试数组array1 
    print(Find(8, array1))   #打印输出结果

力扣(LeetCode)类似题目,代码优化,多了一个前提判断

在一个 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。

解题代码:

class Solution(object):
    def findNumberIn2DArray(self, matrix, target):
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """
        while len(matrix)==0 or len(matrix[0])==0:
            return False

        row = len(matrix)-1
        col = len(matrix[0])-1
        i = row
        j = 0
        while j<=col and i>=0:
            if target<matrix[i][j]:
                i -= 1
            elif target>matrix[i][j]:
                j += 1
            else:
                return True
        return False

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/99858.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!