LeetCode 74 Search a 2D Matrix(Python详解及实现)
来源:互联网 发布:广联达翻样软件多少钱 编辑:程序博客网 时间:2024/05/22 04:40
【题目】
Write an efficient algorithm that searchesfor a value in an m x n matrix. This matrix has the following properties:
Integers in each row are sorted from leftto right.
The first integer of each row is greaterthan the last integer of the previous row.
在一个m*n二维数组中,判断某个元素是否在该数组中。
每一行从左到右递增,每一行的第一个元素比上一行最后一个元素大。
【思路】
思路一:对于每行从左到右递增,从上到下也是递增的。(TLE)
从矩阵的左上角出发,第零行,如果当前值【0,0】比target小,且【0,n-1】比target 大的话,列索引加1,继续比较;如果且【0,n-1】比target小的话,行索引加1,继续 比较。
思路二:先在列二分查找定位列,然后再二分查找,定位行注意边界条件
注意:在列查找的时候,发现low-1小于0时,直接返回False。
【Python实现】
class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
m = len(matrix)
if m == 0 :
return False
n = len(matrix[0])
if n == 0:
return False
low = 0
high = m - 1
while low <= high:
mid = (low + high) // 2
if matrix[mid][0] == target:
return True
elif matrix[mid][0] > target:
high = mid - 1
else:
low = mid + 1
row = low - 1
if row < 0:
row = 0
low = 0
high = n - 1
while low <= high:
mid = (low + high) // 2
if matrix[row][mid] == target:
#print(matrix[row][mid])
return True
elif matrix[row][mid] > target:
high = mid - 1
else:
low = mid + 1
return False
if __name__ == '__main__':
S= Solution()
matrix =[[1, 3, 5, 7],[10, 11, 16, 20],[23, 30, 34, 50]]
target = 20
S.searchMatrix( matrix,target)
- LeetCode 74 Search a 2D Matrix(Python详解及实现)
- 【Leetcode】【python】Search a 2D Matrix
- 【LEETCODE】74-Search a 2D Matrix [Python]
- Leetcode 74 Search a 2D Matrix
- LeetCode 74: Search A 2D Matrix
- LeetCode 74 Search a 2D Matrix
- [leetcode 74] Search a 2D Matrix
- [LeetCode 74]Search a 2D Matrix
- leetcode || 74、Search a 2D Matrix
- leetcode-74 Search a 2D Matrix
- Leetcode[74]-Search a 2D Matrix
- 【Leetcode】Search a 2D Matrix #74
- LeetCode(74) Search a 2D Matrix
- Leetcode #74 Search a 2D Matrix
- Leetcode #74 Search a 2D Matrix
- leetcode 74: Search a 2D Matrix
- Leetcode#74||Search a 2D Matrix
- leetcode 74 : Search a 2D Matrix
- leetcode--Combination Sum
- 莫比乌斯反演学习资料
- UI05-UIView视图的创建
- 设计模式初探-观察者模式
- Noip 2014 无线网络发射器选址
- LeetCode 74 Search a 2D Matrix(Python详解及实现)
- 线程通信基础流程分析
- Dynamics CRM 365 Button自定义之RibbonWorkbench2016
- Swift 学习笔记(一)
- 大型网站架构之分布式消息队列
- 封装类似thinkphp连贯操作数据库的Db类(简单版)。
- linux环境安装指定版本的ruby步骤
- console对象
- leetcode--Combination Sum II