Leetcode-240题:Search a 2D Matrix
2016-10-08 本文已影响20人
八刀一闪
题目
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 in ascending from left to right.
Integers in each column are sorted in ascending from top to bottom.
For example,
Consider the following 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]
]
Given target = 5, return true.
Given target = 20, return false.
思路
从矩阵右上角开始考虑,如果当前元素比所求大,跳转到左一列;如果比所求小,跳到下一行;如果是所求,直接返回。
代码
class Solution(object):
def binarySearch(self, nums, l, r, target):
if l > r:
return False
m = l + (r-l)/2
if nums[m] == target:
return True
elif nums[m] > target:
return self.binarySearch(nums, l, m-1, target)
else:
return self.binarySearch(nums, m+1, r, target)
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if matrix==None or len(matrix)==0:
return False
m = len(matrix)
n = len(matrix[0])
i = 0
j = n-1
while i!=m-1 and j!=0:
if matrix[i][j] == target:
return True
elif matrix[i][j] < target:
i += 1
else:
j -= 1
if i == m-1:
return self.binarySearch(matrix[i][:j+1],0,j,target)
else:
return self.binarySearch([matrix[k][j] for k in range(i,m)],0,m-i-1,target)