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. python 中 打印及格式化字符串的相关方法

    原文 将值转换为字符串 Python 有多种方式将任何值转为字符串: 将它传给 repr() 或 str() 函数. repr() 和 str() 的区别,看几个例子: >>> pr ...

  2. C# 单元测试能过,但Web项目就报错!

    第一印象肯定是两个项目中各有不同的地方 背景: 公司项目采用IBatic+Castle实现 排查过程: 1.sqlmap文件是否一至,并且读取位置也要正确 2.dao.config文件要一至,读取位置 ...

  3. nowcoder 211B - 列队 - [(伪·良心贪心)真·毒瘤暴力]

    题目链接:https://www.nowcoder.com/acm/contest/211/B 题目描述 炎热的早上,gal男神们被迫再操场上列队,gal男神们本来想排列成x∗x的正方形,可是因为操场 ...

  4. JavaScript面向对象之函数构造器的理解

    1,在使用函数创建类时,函数本身也被称为该类的构造器,该类的构造器方法,该类的构造方法,该类的构造函数等等. 2,注意构造器方法是没有返回值的,当创建该类的实例时,必须调用该类的构造方法. 3,获取构 ...

  5. mysql学习【第4篇】:MySQL函数和编程

    狂神声明 : 文章均为自己的学习笔记 , 转载一定注明出处 ; 编辑不易 , 防君子不防小人~共勉 ! mysql学习[第4篇]:MySQL函数 官方文档 : 官方文档 常用函数 分类: 数学函数 , ...

  6. Python操作Mysql数据库——多表组合查询

    前面我们介绍了单张表的查询,包括模糊查询.分组.排序.各种筛选条件等等操作,在实际应用中,查询的数据往往不止局限在一张表里,通常需要多张表在一起进行组合查询,今天我们将会对Mysql当中的多张有关联的 ...

  7. LeetCode 559 Maximum Depth of N-ary Tree 解题报告

    题目要求 Given a n-ary tree, find its maximum depth. The maximum depth is the number of nodes along the ...

  8. LeetCode 700 Search in a Binary Search Tree 解题报告

    题目要求 Given the root node of a binary search tree (BST) and a value. You need to find the node in the ...

  9. scala-数组/列表

    import scala.collection.mutable.ArrayBuffer var ary=Array(1,2,3) println(ary.mkString) println(ary(1 ...

  10. springboot注入properties配置到javabean

    一.再application.properties中添加 二. @Value("${field}")在字段上面加个注解