#!/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
最新推荐文章于 2026-01-05 22:36:07 发布
本文介绍了一个高效的算法,用于在一特殊格式的二维矩阵中查找特定数值。该矩阵每一行的整数从左到右递增排序,并且每行的第一个整数大于前一行的最后一个整数。文章提供了Python实现代码。
297

被折叠的 条评论
为什么被折叠?



