240. Search a 2D Matrix II(二分查找)
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
.
class Solution: def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: i = len(matrix) - 1 j = 0 while j < len(matrix[0]) and i >=0: if matrix[i][j] > target: i-=1 elif matrix[i][j] < target: j+=1 else: return True return False
class Solution: def searchInsert(self, nums: List[int], target: int) -> int: lo = 0 hi = len(nums) - 1 while lo <=hi: mid = lo + (hi-lo)//2 if target < nums[mid]: hi = mid - 1 elif target > nums[mid]: lo = mid + 1 else: return mid return lo
3、可以每行都用二分查找。
class Solution { public: bool searchInsert(vector<int>& nums, int target) { int low = 0, high = nums.size()-1; while(low <= high) { int mid = low + (high - low)/2; if ( target > nums[mid]) { low = mid +1; } else if (target < nums[mid]){ high = mid -1; } else { return true ; } } return false; } bool searchMatrix(vector<vector<int>>& matrix, int target) { for (auto& vec : matrix) { if (searchInsert(vec,target)) { return true; } } return false; } };