File tree Expand file tree Collapse file tree 2 files changed +46
-0
lines changed
Expand file tree Collapse file tree 2 files changed +46
-0
lines changed Original file line number Diff line number Diff line change 1+ Write an efficient algorithm that searches for a value in an * m* x * n* matrix. This matrix has the following properties:
2+
3+ - Integers in each row are sorted from left to right.
4+ - The first integer of each row is greater than the last integer of the previous row.
5+ For example,
6+
7+ Consider the following matrix:
8+ ```
9+ [
10+ [1, 3, 5, 7],
11+ [10, 11, 16, 20],
12+ [23, 30, 34, 50]
13+ ]
14+ ```
15+ Given ** target** = ` 3 ` , return ` true ` .
Original file line number Diff line number Diff line change 1+ public class Solution {
2+ public boolean searchMatrix (int [][] matrix , int target ) {
3+ if (matrix == null || matrix .length == 0 || matrix [0 ].length == 0 )
4+ return false ;
5+
6+ int rowIdx = 0 ;
7+ int colsNum = matrix [0 ].length ;
8+ int rowsNum = matrix .length ;
9+
10+ while (rowIdx < rowsNum && matrix [rowIdx ][colsNum - 1 ] < target )
11+ rowIdx ++;
12+
13+ if (rowIdx == rowsNum )
14+ return false ;
15+
16+ int left = 0 ;
17+ int right = colsNum - 1 ;
18+
19+ while (left <= right ) {
20+ int mid = (left + right ) >> 1 ;
21+ if (matrix [rowIdx ][mid ] < target )
22+ left = mid + 1 ;
23+ else if (matrix [rowIdx ][mid ] > target )
24+ right = mid - 1 ;
25+ else
26+ return true ;
27+ }
28+
29+ return false ;
30+ }
31+ }
You can’t perform that action at this time.
0 commit comments