Last active
November 3, 2020 15:37
-
-
Save ovechkin-dm/8c831e738351676dd34ac87adc1392cf to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public boolean searchMatrix(int[][] matrix, int target) { | |
int rows = matrix.length; | |
if (rows == 0) { | |
return false; | |
} | |
int cols = matrix[0].length; | |
if (cols == 0) { | |
return false; | |
} | |
int rowdiv = (int) Math.sqrt(rows); | |
int coldiv = (int) Math.sqrt(cols); | |
for (int r = 0; r < rows; r += rowdiv) { | |
for (int c = 0; c < cols; c += coldiv) { | |
int endr = Math.min(rows - 1, r + rowdiv); | |
int endc = Math.min(cols - 1, c + coldiv); | |
int begin = matrix[r][c]; | |
int end = matrix[endr][endc]; | |
if (target <= end && target >= begin) { | |
int curc = endc; | |
int curr = r; | |
while (curc >= c && curr <= endr) { | |
if (target > matrix[curr][curc]) { | |
curr += 1; | |
} else if (target < matrix[curr][curc]) { | |
curc -= 1; | |
} else { | |
return true; | |
} | |
} | |
} | |
} | |
} | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment