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:less
Input: matrix = [ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ] target = 13 Output: false
難度:mediumcode
題目:寫算法在m * n的矩陣中查找給定的值。矩陣特徵以下:
矩陣中的每行升序排列。
每行中的的第一個數大於其前一行的最後一個數。ci
思路:從最後一列中找出第一個大於target的值,並記錄下當前行。而後對該行進行二分查找。get
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.it
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; } }