74. Search a 2D Matrix(剑指offer 1)
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.
Example 1:
Input: matrix = [ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ] target = 3 Output: true
Example 2:
Input: matrix = [ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ] target = 13 Output: false
class Solution: def searchMatrix(self, num: List[List[int]], target: int) -> bool: n1 = len(num) n2 = len(num[0]) lo = 0 hi = n1*n2 -1 while lo <=hi: mid = lo +(hi-lo)//2 i = mid //n2 j = mid % n2 if num[i][j] < target: lo = mid + 1 elif target < num[i][j]: hi = mid - 1 else: return True return False
class Solution: def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: n1 = len(matrix) n2 = len(matrix[0]) l = 0 r = n1*n2 - 1 while l <=r : mid = l + (r-l)//2 cur = matrix[mid//n2][mid%n2] if cur == target: return True elif cur > target: r = mid - 1 else: l = mid + 1 return False
1 class Solution { 2 public: 3 bool searchMatrix(vector<vector<int>>& matrix, int target) { 4 // 先根据最后一列二分查找,确定 target 在哪一行。 5 int n = matrix.size(); //3 6 int m = matrix[0].size();//4 7 int low = 0; 8 int high = n -1 ; 9 while(low < high) { 10 int mid = low + (high - low) / 2; 11 if (matrix[mid][m-1] < target) { 12 low = mid + 1; 13 } else if(matrix[mid][m-1] > target) { 14 high = mid ; 15 } else { 16 return true; 17 } 18 } 19 // low is the target 行 20 int wanted_row = low; 21 low = 0; 22 high = m - 1 ; 23 24 while(low < high) { 25 int mid = low + (high - low) /2; 26 if(matrix[wanted_row][mid] < target) { 27 low = mid + 1; 28 } else if (matrix[wanted_row][mid] > target) { 29 high = mid ; 30 } else { 31 return true; 32 } 33 } 34 return matrix[wanted_row][low] == target; 35 } 36 };
1 class Solution { 2 public boolean searchMatrix(int[][] a, int target) { 3 if (a.length<1) 4 return false; 5 int i = 0; 6 int j = a[0].length-1; 7 while(i<a.length && j>=0){ 8 if(target==a[i][j]) 9 return true; 10 else if(target>a[i][j]) 11 i++; 12 else 13 j--; 14 } 15 return false; 16 } 17 }