240.Search a 2D Matrix II
1- Binary Search line by line O(nlogn)
class Solution {
public boolean binarySearch(int[] a, int target){
int n = a.length;
int left = 0;
int right = n - 1;
while(left <= right){
int mid = left + (right - left) / 2;
if(a[mid] == target){
return true;
}
else if(a[mid] > target){
right = mid - 1;
}
else{
left = mid + 1;
}
}
return false;
}
public boolean searchMatrix(int[][] matrix, int target) {
boolean ans;
for(int i = 0; i < matrix.length; i++){
ans = binarySearch(matrix[i], target);
if(ans){
return true;
}
}
return false;
}
}
2-Two Pointer O(m + n)
https://leetcode.com/problems/search-a-2d-matrix-ii/solution/
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int x = matrix.length - 1;
int y = 0;
while(x >= 0 && y < matrix[0].length){
if(matrix[x][y] > target){
x--;
}
else if(matrix[x][y] < target){
y++;
}
else{
return true;
}
}
return false;
}
}