顿搜
飞过闲红千叶,夕岸在哪
类目归类
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.
Consider the following matrix:
[
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
Given target = 3, return true.
public class LeetCode0074 {
public boolean searchMatrix(int[][] matrix, int target) {
if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
return false;
}
int rowLength = matrix.length, col = matrix[0].length - 1;
int row = 0;
while(col >= 0 && row < rowLength){
if(matrix[row][col] == target){
return true;
}
if(matrix[row][col] < target){
row ++;
}
else{
col --;
}
}
return false;
}
public static void main(String[] args) {
LeetCode0074 leetcode = new LeetCode0074();
int[][] matrix = {
{1,3,5,7},
{10,11,16,20},
{23,30,34,50}
};
System.out.println(leetcode.searchMatrix(matrix, 3));
}
}