74. Search a 2D Matrix
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
難度:medium
題目:寫演算法在m * n的矩陣中查詢給定的值。矩陣特徵如下:
矩陣中的每行升序排列。
每行中的的第一個數大於其前一行的最後一個數。
思路:從最後一列中找出第一個大於target的值,並記錄下當前行。然後對該行進行二分查詢。
Runtime: 5 ms, faster than 73.46% of Java online submissions for Search a 2D Matrix.
Memory Usage: 38.8 MB, less than 0.96% of Java online submissions for Search a 2D Matrix.
class Solution { public boolean searchMatrix(int[][] matrix, int target) { if (matrix.length == 0 || matrix[0].length == 0) { return false; } int m = matrix.length, n = matrix[0].length, row = 0; for (int i = 0; i < m; i++) { row = i; if (matrix[i][n - 1] >= target) { break; } } return Arrays.binarySearch(matrix[row], target) >= 0; } }