avatar

Catalog
面试题04. 二维数组中的查找

题目描述

在一个 n * m 的二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
示例:
现有矩阵 matrix 如下:
[
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
]
给定 target = 5,返回 true。
给定 target = 20,返回 false。

解题思路

很有意思的题目,通过判断第一行最后一个和第一列最后一个缩小范围。即当target 小于第一行最后一个时,他肯定小于该列的所有值

代码

Code
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
class Solution:
def findNumberIn2DArray(self, matrix: List[List[int]], target: int) -> bool:
if len(matrix) == 0 or len(matrix[0])==0:
return False
if target < matrix[0][0] or target > matrix[-1][-1]:
return False
H = len(matrix)
W = len(matrix[0])
w = W - 1
while w > 0 :
if matrix[0][w] == target:
return True
if matrix[0][w] > target:
w -= 1
else:
break
h = H - 1
while h > 0:
if matrix[h][0] == target:
return True
if matrix[h][0] > target:
h -=1
else:
break
for i in range(h+1):
for j in range(w+1):
if matrix[i][j] == target:
return True
return False
Author: kim yhow
Link: http://yoursite.com/2020/03/14/面试题04-二维数组中的查找/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.
Donate
  • 微信
    微信
  • 支付寶
    支付寶