-
Notifications
You must be signed in to change notification settings - Fork 13.3k
Expand file tree
/
Copy pathSortedMatrix.java
More file actions
88 lines (79 loc) · 2.78 KB
/
SortedMatrix.java
File metadata and controls
88 lines (79 loc) · 2.78 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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package com.kunal;
import java.util.Arrays;
public class SortedMatrix {
public static void main(String[] args) {
int[][] arr = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
System.out.println(Arrays.toString(search(arr, 9)));
}
// search in the row provided between the cols provided
static int[] binarySearch(int[][] matrix, int row, int cStart, int cEnd, int target) {
while (cStart <= cEnd) {
int mid = cStart + (cEnd - cStart) / 2;
if (matrix[row][mid] == target) {
return new int[]{row, mid};
}
if (matrix[row][mid] < target) {
cStart = mid + 1;
} else {
cEnd = mid - 1;
}
}
return new int[]{-1, -1};
}
static int[] search(int[][] matrix, int target) {
int rows = matrix.length;
int cols = matrix[0].length; // be cautious, matrix may be empty
if (cols == 0){
return new int[] {-1,-1};
}
if (rows == 1) {
return binarySearch(matrix,0, 0, cols-1, target);
}
int rStart = 0;
int rEnd = rows - 1;
int cMid = cols / 2;
// run the loop till 2 rows are remaining
while (rStart < (rEnd - 1)) { // while this is true it will have more than 2 rows
int mid = rStart + (rEnd - rStart) / 2;
if (matrix[mid][cMid] == target) {
return new int[]{mid, cMid};
}
if (matrix[mid][cMid] < target) {
rStart = mid;
} else {
rEnd = mid;
}
}
// now we have two rows
// check whether the target is in the col of 2 rows
if (matrix[rStart][cMid] == target) {
return new int[]{rStart, cMid};
}
if (matrix[rStart + 1][cMid] == target) {
return new int[]{rStart + 1, cMid};
}
// rEnd = rStart+1 (this will cause no error)
/*
Introducing edge checks for cMid so that it does not get out of bounds.
*/
// search in 1st half
if (cMid > 0 && target <= matrix[rStart][cMid - 1]) {
return binarySearch(matrix, rStart, 0, cMid-1, target);
}
// search in 2nd half
if (cMid < cols - 1 && target >= matrix[rStart][cMid + 1] && target <= matrix[rStart][cols - 1]) {
return binarySearch(matrix, rStart, cMid + 1, cols - 1, target);
}
// search in 3rd half
if (cMid > 0 && target <= matrix[rStart + 1][cMid - 1]) {
return binarySearch(matrix, rStart + 1, 0, cMid-1, target);
}
else {
return binarySearch(matrix, rStart + 1, cMid + 1, cols - 1, target);
}
}
}