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
.
注意这道题给出的矩阵,每行都是有序数组,并且每一行的结尾数字是小于下一行的开头数字的。注意这道题与剑指offer上的《面试题3:二维数组中的查找》给出的二维数组的特性是不一样的。这道题有明显的使用二分搜索的特点。
一种做法是我一开始想到,先二分到行,确定一行用于查找,之后再在行里查找,感觉我还是没有把二分越边界的情况想的特别清楚,代码有些冗长,时间复杂度是O(logm+logn),空间复杂度O(1),代码如下:
class Solution(object): def searchMatrix(self, matrix, target): """ :type matrix: List[List[int]] :type target: int :rtype: bool """ if not matrix or not matrix[0] or target < matrix[0][0] or target > matrix[-1][-1]: return False m = len(matrix) n = len(matrix[0]) l = 0 r = m-1 while l < r: mid = l + (r-l)/2 if target > matrix[mid][-1]: l = mid+1 elif target < matrix[mid][0]: r = mid-1 else: l = r = mid break if l != r: return False if target < matrix[l][0] or target > matrix[l][-1]: return False k = l l = 0 r = n-1 while l <= r: mid = l+(r-l)/2 if target < matrix[k][mid]: r = mid -1 elif target > matrix[k][mid]: l = mid +1 else: return True return False
另外一种简洁直接的解法为将二维数组看作一维排序数组来考虑,唯一需要注意的是如何将mid的值转化为实际二维数组中的index,注意是除以行宽呀,盆友。时间复杂度O(log(mn))=O(log(m)+log(n)),代码如下,简洁许多:
class Solution(object): def searchMatrix(self, matrix, target): """ :type matrix: List[List[int]] :type target: int :rtype: bool """ if not matrix or not matrix[0]: return False m = len(matrix) n = len(matrix[0]) l = 0 r = m*n -1 while l <= r: mid = l + (r-l)/2 if target < matrix[mid/n][mid%n]: r = mid -1 elif target > matrix[mid/n][mid%n]: l = mid +1 else: return True return False
posted on 2016-05-13 11:59 Sheryl Wang 阅读(129) 评论(0) 编辑 收藏 举报