#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
Search a 2D Matrix
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.
'''
class Solution(object):
def binary_search(self,l,length,target):
if not l or length == 0:
return False
left,right = 0,length - 1
while left <= right:
mid = (left + right)/2
if l[mid] == target:
return True
elif l[mid] > target:
right = mid - 1
else:
left = mid + 1
return False
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
row_length,col_length = len(matrix),len(matrix[0])
if row_length == 0 or col_length == 0:
return False
index = 0
while index < row_length:
if matrix[index][0] <= target and matrix[index][col_length - 1] >= target:
return self.binary_search(matrix[index],col_length,target)
index += 1
return False
if __name__ == "__main__":
s = Solution()
b = [[1, 3, 5, 7],[10, 11, 16, 20],[23, 30, 34, 50]]
print s.searchMatrix(b,12)
40 leetcode - Search a 2D Matrix
最新推荐文章于 2024-10-08 10:36:00 发布