LeetCode 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.
For example,
Consider the following matrix:
[ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ]
Given target = 3
, return true
.
题目标签:Array
题目给了我们一个有序的矩阵,让我们找target是否在矩阵中。首先我们分析,如果我们知道了target 在哪一行的话,直接用binary search 就可以了。所以第一步可以用binary search 来搜索第一列,确认target在哪一行。在用一次二分法对于那一行,找出target。
Java Solution:
Runtime beats 71.85%
完成日期:07/23/2017
关键词:Array
关键点:用二分法两次
1 public class Solution 2 { 3 public boolean searchMatrix(int[][] matrix, int target) 4 { 5 if(matrix.length == 0 || matrix[0].length == 0) 6 return false; 7 if(target < matrix[0][0] || target > matrix[matrix.length-1][matrix[0].length-1]) 8 return false; 9 // first determine which row the target is in 10 int top = 0; 11 int bottom = matrix.length-1; 12 13 while(top <= bottom) 14 { 15 int mid = top + (bottom - top) / 2; 16 17 if(matrix[mid][0] == target) 18 return true; 19 else if(matrix[mid][0] > target) 20 bottom = mid - 1; 21 else 22 top = mid + 1; 23 } 24 25 int rowNum = bottom; 26 27 // use binary search for this row 28 int left = 0; 29 int right = matrix[0].length-1; 30 31 while(left <= right) 32 { 33 int mid = left + (right - left) / 2; 34 35 if(matrix[rowNum][mid] == target) 36 return true; 37 else if(matrix[rowNum][mid] < target) 38 left = mid + 1; 39 else 40 right = mid - 1; 41 42 } 43 44 return false; 45 } 46 }
参考资料:
http://www.cnblogs.com/grandyang/p/4323301.html
LeetCode 算法题目列表 - LeetCode Algorithms Questions List