https://oj.leetcode.com/problems/search-a-2d-matrix/
思路1
思路就是做两次BS. 第一次定位行,第二次定位列
O(logm + logn)
http://blog.csdn.net/linhuanmars/article/details/24216235
python code
http://jelices.blogspot.hk/2014/05/leetcode-python-search-2d-matrix.html
自己重写code
class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
m, n = len(matrix), len(matrix[0])
low = 0
high = m - 1
while low <= high:
mid = (low + high) / 2
if matrix[mid][0] == target:
return True
elif matrix[mid][0] < target:
low = mid + 1
else:
high = mid - 1
low -= 1
x = low
low, high = 0, len(matrix[x]) - 1
while low <= high:
mid = (low + high) / 2
if matrix[x][mid] == target:
return True
elif matrix[x][mid] < target:
low = mid + 1
else:
high = mid - 1
return False
思路2 直接在matrix上搜索
http://www.cnblogs.com/zuoyuan/p/3770061.html
class Solution:
# @param matrix, a list of lists of integers
# @param target, an integer
# @return a boolean
def searchMatrix(self, matrix, target):
i = 0; j = len(matrix[0]) - 1
while i < len(matrix) and j >= 0:
if matrix[i][j] == target: return True
elif matrix[i][j] > target: j -= 1
else: i += 1
return False