Leetcode 240. Search a 2D Matrix II

https://leetcode.com/problems/search-a-2d-matrix-ii/

Medium

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 in ascending from left to right.
  • Integers in each column are sorted in ascending from top to bottom.

Example:

Consider the following matrix:

[
  [1,   4,  7, 11, 15],
  [2,   5,  8, 12, 19],
  [3,   6,  9, 16, 22],
  [10, 13, 14, 17, 24],
  [18, 21, 23, 26, 30]
]

Given target = 5, return true.

Given target = 20, return false.


 1 class Solution:
 2     def searchMatrix(self, matrix, target):
 3         """
 4         :type matrix: List[List[int]]
 5         :type target: int
 6         :rtype: bool
 7         """
 8         if not matrix or len(matrix) == 0 or len(matrix[0]) == 0:
 9             return False
10         
11         row, column = 0, len(matrix[0]) - 1
12         
13         while row < len(matrix) and column >= 0:
14             if target == matrix[row][column]:
15                 return True
16             elif target < matrix[row][column]:
17                 column -= 1
18             else:
19                 row += 1
20         
21         return False
22     
23     def searchMatrix2(self, matrix, target):
24         """
25         :type matrix: List[List[int]]
26         :type target: int
27         :rtype: bool
28         """
29         return any(target in row for row in matrix)
30     
31     def searchMatrix3(self, matrix, target):
32         """
33         :type matrix: List[List[int]]
34         :type target: int
35         :rtype: bool
36         """
37         if not matrix or len(matrix) == 0 or len(matrix[0]) == 0:
38             return False
39         
40         def helper(nums, target):
41             left, right = 0, len(nums) - 1
42             
43             while left <= right:
44                 # remember to use // 2
45                 middle = (left + right) // 2
46 
47                 if target == nums[middle]:
48                     return True
49                 elif target < nums[middle]:
50                     right = middle - 1
51                 else:
52                     left = middle + 1
53             
54             return False
55         
56         for row in matrix:
57             if helper(row, target):
58                 return True
59         
60         return False
View Python Code

 

posted on 2019-09-03 17:44  浩然119  阅读(162)  评论(0编辑  收藏  举报