編寫(xiě)一個(gè)高效的算法來(lái)搜索 m x n 矩陣 matrix 中的一個(gè)目標(biāo)值 target嚼黔。該矩陣具有以下特性:
每行的元素從左到右升序排列。
每列的元素從上到下升序排列瓣颅。
示例:
現(xiàn)有矩陣 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檬姥。
思路是用循環(huán)遍歷的方法進(jìn)行比較曾我,從矩陣的左下角或者右上角開(kāi)始遍歷,這樣知道了比較的結(jié)果是大還是小健民,就知道了對(duì)應(yīng)的前進(jìn)方向抒巢。
我的代碼是使用從右上角開(kāi)始遍歷:
class Solution:
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if not matrix:
return False
if not matrix[0]:
return False
rows = len(matrix)
cols = len(matrix[0])
row,col = 0,cols - 1
while True:
if row < rows and col >= 0:
if matrix[row][col] == target:
return True
elif matrix[row][col] < target:
row += 1
else:
col -= 1
else:
return False
運(yùn)行結(jié)果后傻眼了,代碼只超過(guò)了33的用戶(hù)秉犹,好郁悶啊虐秦。以后會(huì)繼續(xù)尋找更好的方法解決這道題!