-
Notifications
You must be signed in to change notification settings - Fork 2.4k
Expand file tree
/
Copy pathSearchIn2DMatrix.java
More file actions
38 lines (27 loc) · 1.12 KB
/
Copy pathSearchIn2DMatrix.java
File metadata and controls
38 lines (27 loc) · 1.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// Time Complexity : O(log m*n)
// Space Complexity : O(1)
// Did this code successfully run on Leetcode : YES
// Any problem you faced while coding this : NO
// Your code here along with comments explaining your approach in three sentences only
// This code performs a binary search on a 2D matrix by treating it as a single, sorted 1D array of length times n.
// It calculates the 2D coordinates using mid / n and mid % n to check the target, efficiently finding the value in O(log(m x n)) time.
public class SearchIn2DMatrix {
public boolean searchMatrix(int[][] matrix, int target) {
int m = matrix.length;
int n = matrix[0].length;
int low = 0, high = m*n-1;
while(low <= high){
int mid = low + (high - low)/2;
int r = mid / n;
int c = mid % n;
if(matrix[r][c] == target){
return true;
}else if(matrix[r][c] > target){
high = mid - 1;
}else{
low = mid + 1;
}
}
return false;
}
}