forked from architsingla13/InterviewBit-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMatrixMedian.java
More file actions
64 lines (50 loc) · 1.36 KB
/
MatrixMedian.java
File metadata and controls
64 lines (50 loc) · 1.36 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
package BinarySearch;
import java.util.ArrayList;
import java.util.Arrays;
/**
* Author - archit.s
* Date - 02/10/18
* Time - 12:16 PM
*/
public class MatrixMedian {
public int findMedian(ArrayList<ArrayList<Integer>> A) {
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
int r = A.size();
int c = A.get(0).size();
int desired = (r*c+1)/2;
for (ArrayList<Integer> aA : A) {
for (int j = 0; j < c; j++) {
if (aA.get(j) < min) {
min = aA.get(j);
}
if (aA.get(j) > max) {
max = aA.get(j);
}
}
}
while(min < max){
int place = 0;
int mid = min + (max-min)/2;
int get = 0;
for (ArrayList<Integer> aA : A) {
get = Arrays.binarySearch(aA.toArray(), mid);
if (get < 0) {
get = Math.abs(get) - 1;
} else {
while (get < c && aA.get(get) == mid) {
get++;
}
}
place = place + get;
}
if(place < desired){
min = mid + 1;
}
else{
max = mid;
}
}
return min;
}
}