74. 搜索二维矩阵

​题目来源:

LeetCode题目:74. 搜索二维矩阵 - 力扣(LeetCode)

解题思路:

两次二分。第一次二分寻找第一列中小于等于target的最大值,第二次 在该行中找到小于等于target的最大值,最后判断是否存在该值及该值是否是 target。

解题代码:

复制代码
#python3
class Solution:
    def getIndex(matrix:List[int],target:int)->int:
        left=0
        right=len(matrix)-1
        while(left<right):
            mid=(left+right)//2+1
            if matrix[mid]==target:
                return mid
            elif matrix[mid]<target:
                left=mid
            else:
                right=mid-1
        return left


    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        n0=[]
        for i in range(len(matrix)):
            n0.append(matrix[i][0])
        row=Solution.getIndex(n0,target)
        if row<0 or  row>=len(matrix):
            return False
        column=Solution.getIndex(matrix[row],target)
        if column<0 or column>=len(matrix[0]):
            return False
        return matrix[row][column]==target
复制代码

总结:

官方题解给出了两种解法。第一个是两次二分。第二个是一次二分,讲二维数组拼接为一维数组后再进行二分查找。


相关推荐
文丑颜不良啊1 天前
LeetCode1661~1680题目解析
java·leetcode
文丑颜不良啊1 天前
LeetCode1721~1740题目解析
java·leetcode
文丑颜不良啊1 天前
LeetCode1681~1700题目解析
java·leetcode
开开心心就好1 天前
网页图片批量下载工具,输入链接就保存
服务器·算法·leetcode·支持向量机·pdf·ocr·1024程序员节
圣保罗的大教堂1 天前
leetcode 462. 最小操作次数使数组元素相等 II 中等
leetcode
Navigator_Z1 天前
LeetCode //C - 1313. Decompress Run-Length Encoded List
c语言·算法·leetcode
Nuanyt1 天前
LeetCode Hot 100 链表专题(四)· 3 题(Java)
java·算法·leetcode·链表·双指针
圣保罗的大教堂2 天前
leetcode 453. 最小操作次数使数组元素相等 中等
leetcode
Tisfy2 天前
LeetCode 0453.最小操作次数使数组元素相等:两次遍历(反向思维)
算法·leetcode·题解·遍历·反向思维
君万2 天前
【LeetCode每日一题】回溯:46. 全排列 78. 子集 39. 组合总和
算法·leetcode·go