Skip to content

Commit 0826a22

Browse files
committed
Solution for: search 2d matrix
1 parent c6402c5 commit 0826a22

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

src/leetcode/Search2DMatrix.java

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package leetcode;
2+
3+
public class Search2DMatrix {
4+
5+
public static void main(String[] args) {
6+
Search2DMatrix test = new Search2DMatrix();
7+
int[][] ma = new int[][] {{1,3,5,7}, {10, 11, 16, 20}, {23, 30, 34, 50}};
8+
int[][] ma2 = new int[][] {{1,1}};
9+
//System.out.println(test.searchMatrix(ma, 3));
10+
System.out.println(test.searchMatrix(ma2, 2));
11+
12+
}
13+
14+
public boolean searchMatrix(int[][] matrix, int target) {
15+
if(matrix==null || matrix.length==0) return false;
16+
int n = matrix.length;
17+
int m = matrix[0].length;
18+
int l=0; int p= n*m-1;
19+
while(l<=p){
20+
int mid = (l+p)/2;
21+
int value = matrix[mid/m][mid%m];
22+
if(value==target) return true;
23+
if(target<value)
24+
p= mid-1;
25+
else
26+
l= mid+1;
27+
28+
}
29+
return false;
30+
}
31+
32+
}

0 commit comments

Comments
 (0)