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. 从右上角开始找,i.e. 当前行最大,当前列最小的开始。因为横竖都是升序,所以如果target > current,必然不在当前行;如果target < current,必然不在当前列。
- 2. Python any() function
- 3. 对每一行进行二分查找。记得Python3要用整除//, i.e. middle = (left + right) // 2。
- https://leetcode.com/problems/search-a-2d-matrix-ii/discuss/66140/My-concise-O(m%2Bn)-Java-solution
- https://leetcode.com/problems/search-a-2d-matrix-ii/discuss/66163/C%2B%2B-two-solutions-(O(m%2Bn)-O(mlogn))
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