Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:

  • Integers in each row are sorted from left to right.
  • The first integer of each row is greater than the last integer of the previous row.

Example 1:

Input:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 3
Output: true

Example 2:

Input:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 13
Output: false 1) 第一种思路为 因为每行是sorted, 并且后面的row要比前面的要大, 所以我们可以将它看做是一维的sorted array 去处理, 然后去Binary Search, 只是需要注意的是num = matrix[mid//lrc[1]:列数][mid%lrc[0]:行数]. 2) 第二种思路为, 找到可能在某一行(last index <= target),然后在该行中做常规的binary search
Code 1)
class Solution:
def searchMatrix(self, matrix, target):
if not matrix or len(matrix[0]) == 0: return False
lrc = [len(matrix), len(matrix[0])]
l, r = 0, lrc[0]*lrc[1] -1
while l + 1 < r:
mid = l + (r - l)//2
num = matrix[mid//lrc[1]][mid%lrc[1]]
if num > target:
r = mid
elif num < target:
l = mid
else:
return True
if target in [matrix[l//lrc[1]][l%lrc[1]], matrix[r//lrc[1]][r%lrc[1]]]:
return True
return False

2)

class Solution:
def searchMatrix(self, matrix, target):
if not matrix or len(matrix[0]) == 0 or matrix[0][0] > target or matrix[-1][-1] < target:
return False
colNums = list(zip(*matrix))[0] # first column
# find the last index <= target
l, r = 0, len(colNums) -1
while l + 1 < r:
mid = l + (r - l)//2
if colNums[mid] > target:
r = mid
elif colNums[mid] < target:
l = mid
else:
return True
rowNums = matrix[r] if colNums[r] <= target else matrix[l]
l, r = 0, len(rowNums) - 1
while l + 1 < r:
mid = l + (r -l)//2
if rowNums[mid] > target:
r = mid
elif rowNums[mid] < target:
l = mid
else:
return True
if target in [rowNums[l], rowNums[r]]: return True
return False

[LeetCode] 74. Search a 2D Matrix_Medium tag: Binary Search的更多相关文章

  1. [LeetCode] 34. Find First and Last Position of Element in Sorted Array == [LintCode] 61. Search for a Range_Easy tag: Binary Search

    Description Given a sorted array of n integers, find the starting and ending position of a given tar ...

  2. [LeetCode] 33. Search in Rotated Sorted Array_Medium tag: Binary Search

    Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e. ...

  3. [LeetCode] 278. First Bad Version_Easy tag: Binary Search

    You are a product manager and currently leading a team to develop a new product. Unfortunately, the ...

  4. 【一天一道LeetCode】#109. Convert Sorted List to Binary Search Tree

    一天一道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder's Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (一)题目 Given a ...

  5. LeetCode 33 Search in Rotated Sorted Array [binary search] <c++>

    LeetCode 33 Search in Rotated Sorted Array [binary search] <c++> 给出排序好的一维无重复元素的数组,随机取一个位置断开,把前 ...

  6. [LeetCode] 235. Lowest Common Ancestor of a Binary Search Tree 二叉搜索树的最小共同父节点

    Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BS ...

  7. 【LeetCode】109. Convert Sorted List to Binary Search Tree 解题报告(Python)

    [LeetCode]109. Convert Sorted List to Binary Search Tree 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id ...

  8. leetcode 74. Search a 2D Matrix 、240. Search a 2D Matrix II

    74. Search a 2D Matrix 整个二维数组是有序排列的,可以把这个想象成一个有序的一维数组,然后用二分找中间值就好了. 这个时候需要将全部的长度转换为相应的坐标,/col获得x坐标,% ...

  9. [LeetCode] 704. Binary Search_Easy tag: Binary Search

    Given a sorted (in ascending order) integer array nums of n elements and a target value, write a fun ...

随机推荐

  1. Xshell登录Ubuntu12.04

    Ubuntu安装ssh服务: sudo apt-get install openssh-server 打开Xshell,选择“新建”,“连接”设置里选择SSH,主机填入需要连接的主机的IP地址.在“用 ...

  2. net abp core的appservice中访问httpcontext对象

    private readonly IHttpContextAccessor _httpContext; /// <summary> /// Initializes a new instan ...

  3. VBS数组导出到Excel

    <script language="vbscript"> dim arr(9999,4) for i=0 to 9999 for j = 0 to 4 arr(i,j) ...

  4. MySQL主从同步添加至zabbix监控

    参考文档:https://blog.csdn.net/hellowidow_2020/article/details/78985368    https://www.cnblogs.com/cdjia ...

  5. 常见的压缩文件格式案例tarZ

    在AIX上最常见的压缩文件就是.tar压缩格式的文件了.  而除了tar文件以外,有时会遇到数据是用其它的压缩文件格式,所以偶顺手整理了一些常见的压缩文件格式,在AIX要怎么解压缩 : 一. .tar ...

  6. hdu6397 Character Encoding 母函数解约束条件下多重集

    http://acm.hdu.edu.cn/showproblem.php?pid=6397 原问题的本质是问m个元素的多重集S,每一种类型的对象至多出现n-1次的S的k组合的个数是多少? 等价于 x ...

  7. H. GSS and Simple Math Problem 高精度乘法模板

    链接:https://www.nowcoder.com/acm/contest/104/G来源:牛客网 题目描述 Given n positive integers , your task is to ...

  8. [development][endian] 字节序

    首先字节序很不好理解, 其次,理解了又不好记住. 除了字节序, 还有位序. 那么到底怎么记住呢? 大端序,小端序还有另一个名字, 大尾序,小尾序. 这样就记住了, 我们以16进制打印一个数之后, 尾部 ...

  9. [administrative][CentOS][NetworkManager] 万恶的NetworkManager到底怎么用

    这好像是第三次不得不去学会NetworkManager的用法,可是它真的很难用.社区里无人不吐槽. 然而,还是要用! 这次从redhat的文档入手,也许可以成功 --! https://access. ...

  10. DateTimePicker用法

    将DateTimePicker的Format属性中加入日期格式设成 'yyyy-MM-dd HH:mm',注意大小写 , 将kind设置为dtkTime即可,可以在每次Form onShow时将Dat ...