题目
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] ]
思路
我这里提供了3个解法
1.解法一就是一个一个搞,大家都会的
2.解法二就是先找每一行的最后一个数字,因为这个2维数组是一个有序的,所以通过判断每一行的最后一个数字可以知道我们要比较的数字在不在当前行
步骤: 一。如果在这一行,那么从这一行的最后一列往前面移动,如果遍历过了该行的所有列,而且没有找到,那么最后的结果就是没有找到
二。如果不在这一行,那么移动到下一行,然后在比较。
3.解法三就是用二分法来做。把2维数组看成是一维数组。
代码
解法一就不弄了,直接从解法二开始
解法二:
public class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int row = 0;
int col = matrix[0].length-1;
for(;row< matrix.length&&col>=0;)
{
if(matrix[row][col] == target)
return true;
else if ( matrix[row][col] < target)
{
row++;
}
else
{
col--;
}
}
return false;
}
}
解法三:
public class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int row = matrix.length;
int col = matrix[0].length;
int end = row * col -1;
int begin = 0;
while( begin <= end )
{
int middle = ( end +begin )/2;
if( matrix[middle/col][middle%col] == target)
{
return true;
}
else if (matrix[middle/col][middle%col] < target)
{
begin = (middle/col)*col+middle%col+1;
}
else
{
end = (middle/col)*col+middle%col-1;
}
}
return false;
}
}