[LeetCode]题解(python):074-Search a 2D Matrix


题目来源


https://leetcode.com/problems/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.

题意分析


Input:  a matrix and a target to query

Output: True or False

Conditions:在矩阵中查找元素,注意矩阵是有序的


题目思路


先在列二分查找定位哪一列,然后再行二分查找,注意边界条件

PS:其实直接在列查找的时候,发现low-1小于0时,直接返回False就可以了,但是所贴代码可以移植到插入元素的二分排序里面,为了统一就没有改动了。


AC代码(Python)


 1 __author__ = 'YE'
 2 
 3 class Solution(object):
 4     def searchMatrix(self, matrix, target):
 5         """
 6         :type matrix: List[List[int]]
 7         :type target: int
 8         :rtype: bool
 9         """
10         m = len(matrix)
11         n = len(matrix[0])
12         low = 0
13         high = m - 1
14 
15         while low <= high:
16             mid = (low + high) / 2
17             if matrix[mid][0] == target:
18                 return True
19             elif matrix[mid][0] > target:
20                 high = mid - 1
21             else:
22                 low = mid + 1
23         row = low - 1
24         if row < 0:
25             row = 0
26 
27         low = 0
28         high = n - 1
29 
30         while low <= high:
31             mid = (low + high) / 2
32             if matrix[row][mid] == target:
33                 return True
34             elif matrix[row][mid] > target:
35                 high = mid - 1
36             else:
37                 low = mid + 1
38         return False
39 
40 matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,50]]
41 target = 16
42 print(Solution().searchMatrix(matrix,target))
原文地址:https://www.cnblogs.com/loadofleaf/p/5097431.html