LeetCode 74. Search a 2D Matrix(搜索二维矩阵)

时间:2023-03-08 21:22:37
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

关键点:用二分法两次

 public class Solution
{
public boolean searchMatrix(int[][] matrix, int target)
{
if(matrix.length == 0 || matrix[0].length == 0)
return false;
if(target < matrix[0][0] || target > matrix[matrix.length-1][matrix[0].length-1])
return false;
// first determine which row the target is in
int top = 0;
int bottom = matrix.length-1; while(top <= bottom)
{
int mid = top + (bottom - top) / 2; if(matrix[mid][0] == target)
return true;
else if(matrix[mid][0] > target)
bottom = mid - 1;
else
top = mid + 1;
} int rowNum = bottom; // use binary search for this row
int left = 0;
int right = matrix[0].length-1; while(left <= right)
{
int mid = left + (right - left) / 2; if(matrix[rowNum][mid] == target)
return true;
else if(matrix[rowNum][mid] < target)
left = mid + 1;
else
right = mid - 1; } return false;
}
}

参考资料:

http://www.cnblogs.com/grandyang/p/4323301.html

LeetCode 算法题目列表 - LeetCode Algorithms Questions List