leetcode 【Search a 2D Matrix 】python 实现

题目

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.

 

For example,

Consider the following matrix:

[
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]

Given target = 3, return true.

 

代码:oj测试通过 Runtime: 75 ms

复制代码
 1 class Solution:
 2     # @param matrix, a list of lists of integers
 3     # @param target, an integer
 4     # @return a boolean
 5     def searchInline(self, line, target):
 6         start = 0
 7         end = len(line)-1
 8         while start <= end :
 9             if start == end :
10                 return [False,True][line[start]==target]
11             if start+1 == end :
12                 if line[start]==target or line[end]==target :
13                     return True
14                 else:
15                     return False
16             mid=(start+end)/2
17             if line[mid]==target :
18                 return True
19             elif line[mid]>target :
20                 end = mid-1
21             else :
22                 start = mid+1
23 
24     def searchMatrix(self, matrix, target):
25         if len(matrix) == 0 :
26             return False
27         
28         if len(matrix) == 1 :
29             return self.searchInline(matrix[0], target)
30             
31         if len(matrix) == 2 :
32             return self.searchInline([matrix[1],matrix[0]][matrix[1][0]>target], target)\
33             
34         start = 0
35         end = len(matrix)-1
36         while start <= end :
37             if start == end:
38                 return self.searchInline(matrix[start],target)
39             if start+1 == end:
40                 if matrix[start][0] <= target and matrix[end][0] > target:
41                     return self.searchInline(matrix[start],target)
42                 if matrix[end][0] < target :
43                     return self.searchInline(matrix[end],target)
44             mid = (start+end+1)/2
45             if matrix[mid][0] <= target and matrix[mid+1][0] > target:
46                 return self.searchInline(matrix[mid],target)
47             elif matrix[mid][0] > target :
48                 end = mid-1
49             else :
50                 start = mid+1
复制代码

 

思路

先按行二分查找,再按列二分查找。

代码写的比较繁琐。

posted on   承续缘  阅读(292)  评论(0编辑  收藏  举报

编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示