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. ERP项目实施记录04

    周二做了计划部门的需求调查,提到现有计划(一天计划)的准确率仅有60~70%,每天下来都有30%~40%不能达成. 计划部门提出的需求更多是基于Excel操作思路,要求未来的系统要有更多的" ...

  2. 怎样将M4A音频格式转换成MP3格式

    因为MP3音频格式应用的广泛性,所以很多时候我们都需要将不同的音频格式转换成MP3格式的,那么如果我们需要将M4A音频格式转换成MP3格式,我们应该怎样进行实现呢?下面我们就一起来看一下吧. 操作步骤 ...

  3. 计蒜客 31434 - 广场车神 - [DP+前缀和]

    题目链接:https://nanti.jisuanke.com/t/31434 小 D 是一位著名的车手,他热衷于在广场上飙车.每年儿童节过后,小 D 都会在广场上举行一场别样的车技大赛. 小 D 所 ...

  4. java8集合--LinkedList纯源码

    package Queue; import java.util.*; import java.util.function.Consumer; /** * 双端队列主要实现list接口和Deque接口, ...

  5. zookeeper的Java客户端API

    zookeeper作为一个分布式服务框架,主要用来解决分布式数据一致性问题,对多种语言提供了API.这里主要记录下JAVA客户端API的使用. 1.创建会话 客户端可以通过创建一个ZooKeeper实 ...

  6. linux:基本概念和操作

    1. 终端 Linux 默认提供了 6 个纯命令行界面的 “terminal”(准确的说这里应该是 6 个 virtual consoles)来让用户登录,在物理机系统上你可以通过使用[Ctrl]+[ ...

  7. python运算符,数据类型,数据类型操作,三目运算,深浅拷贝

    算数运算符: Py2中精确除法需要导入:from __future__ import division,(符由特  ,将来的.滴未省,除法) py3不需要导入 赋值运算符: 比较运算符: 成员运算符: ...

  8. linux strtock()函数使用问题

    strtok()原型:char * strtok(char *s, const char *delim); 函数说明:strtok()用来将字符串分割成一个个片段.参数s 指向欲分割的字符串,参数de ...

  9. Xshell远程连接 与 Xftp文件传输

    刚开始接触Linux的时候,会想我该怎么在Windows连接到另一台Linux服务器,怎么把我Windows上的文件放到我Linux上面,网上搜索之后,知道可以用Xshell远程连接到Linux,用X ...

  10. 使用Redis 计数器防止刷接口

    业务需求中经常有需要用到计数器的场景:为了防止恶意刷接口,需要设置一个接口每个IP一分钟.一天等的调用次数阈值:为了降低费用,限制发送短信的次数等.使用Redis的Incr自增命令可以轻松实现以上需求 ...