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.
题意:
编写一个有效的算法,在m×n矩阵中搜索一个值。这个矩阵具有以下属性:
每行中的整数从左到右排序。
每一行的第一个整数大于前一行的最后一个整数。
思路:
二分查找,因为是按行排序好的二维数组,所以直接把二维数组看做一维数组,一次二分查找搞定。
n m 的矩阵m可以转化为一个一维数组 => matrix[x][y] => a[x m + y]
一维数组转化为n * m的矩阵m => a[x] =>matrix[x / m][x % m];
1 | class Solution { |
Java Code
1 | class Solution { |