240. Search a 2D Matrix II
Last updated
Last updated
/**
* Time complexity :
* Space complexity : O(1)
*/
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if(matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return false;
}
for(int[] arr: matrix) {
if(binarySearch(arr, target) != -1) {
return true;
}
}
return false;
}
private int binarySearch(int[] arr, int key) {
int n = arr.length;
if(key < arr[0] || key > arr[n-1]) {
return -1;
}
int low = 0, high = n-1;
while(low <= high) {
int mid = (low + high)/2;
if(arr[mid] == key) {
return mid;
}
if(arr[mid] < key) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1;
}
}/**
* Time complexity : O(n+m)
* Space complexity : O(1)
*/
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if(matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return false;
}
int row = matrix.length-1, col = 0;
while(row >= 0 && col < matrix[0].length) {
int value = matrix[row][col];
if(value > target) {
row--;
} else if(value < target) {
col++;
} else {
return true;
}
}
return false;
}
}