File tree Expand file tree Collapse file tree 1 file changed +5
-22
lines changed
src/main/java/com/thealgorithms/matrix Expand file tree Collapse file tree 1 file changed +5
-22
lines changed Original file line number Diff line number Diff line change 22
33/**
44 * Search a 2D Matrix
5- * Each row is sorted left to right, and the first element of each row
6- * is greater than the last element of the previous row.
7- *
8- * Time Complexity: O(log(m*n))
9- * Space Complexity: O(1)
5+ * Reference: https://leetcode.com/problems/search-a-2d-matrix/
106 */
117public class Search2DMatrix {
128
13- /**
14- * Searches for a target value in a 2D matrix using binary search.
15- *
16- * @param matrix the 2D matrix
17- * @param target the value to search
18- * @return true if found, false otherwise
19- */
209 public static boolean searchMatrix (int [][] matrix , int target ) {
2110 if (matrix == null || matrix .length == 0 || matrix [0 ].length == 0 ) {
2211 return false ;
2312 }
2413
2514 int rows = matrix .length ;
2615 int cols = matrix [0 ].length ;
27-
2816 int left = 0 ;
2917 int right = rows * cols - 1 ;
3018
3119 while (left <= right ) {
3220 int mid = (left + right ) / 2 ;
33-
3421 int midValue = matrix [mid / cols ][mid % cols ];
3522
36- if (midValue == target ) {
37- return true ;
38- } else if (midValue < target ) {
39- left = mid + 1 ;
40- } else {
41- right = mid - 1 ;
42- }
23+ if (midValue == target ) return true ;
24+ else if (midValue < target ) left = mid + 1 ;
25+ else right = mid - 1 ;
4326 }
44-
4527 return false ;
4628 }
4729}
30+
You can’t perform that action at this time.
0 commit comments