74. Search a 2D Matrix
https://leetcode.com/problems/search-a-2d-matrix/#/solutions
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. For example, Consider the following matrix: [ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ] Given target = 3, return true.
考点只有一个:2D array 降维成 1D array 的 index trick.
public boolean searchMatrix(int[][] matrix, int target) { // write your code here if (matrix.length == 0) { return false; } if (matrix[0].length == 0) { return false; } int n = matrix.length; int m = matrix[0].length; int low = 0, high = m * n - 1; while (low + 1 < high) { int mid = low + (high - low) / 2; int x = mid / m, y = mid % m; if (matrix[x][y] == target){ return true; } else if (matrix[x][y] > target){ high = mid; } else { low = mid; } } if (matrix[low / m][low % m] == target || matrix[high / m][high % m] == target) { return true; } return false; }