1. Description
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.
2. Runtime Distribution
3. Submission Details
4. Example
Consider the following matrix:
[
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
Given target = 3, return true.
5. Code
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));
}
}
Comments | NOTHING