zoukankan      html  css  js  c++  java
  • Leetcode练习(Python):二分查找类:第240题:搜索二维矩阵 II:编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target。该矩阵具有以下特性: 每行的元素从左到右升序排列。 每列的元素从上到下升序排列。

    题目:
    搜索二维矩阵 II:编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target。该矩阵具有以下特性:  每行的元素从左到右升序排列。 每列的元素从上到下升序排列。
    思路:
    二分查找常规思路。
    程序:
    class Solution:
        def searchMatrix(self, matrix, target):
            """
            :type matrix: List[List[int]]
            :type target: int
            :rtype: bool
            """
            if not matrix:
                return False
            row = len(matrix)
            column = len(matrix[0])
            if row == 0:
                return False
            if column == 0:
                return False
            for index in range(row):
                if target >= matrix[index][0] and target <= matrix[index][column - 1]:
                    left_index = 0
                    right_index = column - 1
                    while left_index <= right_index:
                        middle_index = (left_index + right_index) // 2
                        if matrix[index][middle_index] == target:
                            return True
                        elif matrix[index][middle_index] > target:
                            right_index = middle_index - 1
                        else:
                            left_index = middle_index + 1
            return False
  • 相关阅读:
    LINQ标准查询操作符及例子(转载)
    Winform Combox 下拉模糊匹配
    在RowDataBound事件中取值的几种方法 转载
    shell脚本作业练习题8.6
    7.31.... 简单的python代码
    shell 脚本——第一节课 bash的基本特性
    shell 脚本——第二节课 重定向和管道符
    730
    应用范例:解析 Yahoo 奇摩股市的各档股票资讯HtmlAgilityPack
    微软一个罕为人知的无敌命令
  • 原文地址:https://www.cnblogs.com/zhuozige/p/12874802.html
Copyright © 2011-2022 走看看