-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathMatrixMedian.java
More file actions
147 lines (91 loc) · 2.61 KB
/
MatrixMedian.java
File metadata and controls
147 lines (91 loc) · 2.61 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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
/*
Matrix Median
Problem Description
Given a matrix of integers A of size N x M in which each row is sorted.
Find and return the overall median of the matrix A.
NOTE: No extra memory is allowed.
NOTE: Rows are numbered from top to bottom and columns are numbered from left to right.
Problem Constraints
1 <= N, M <= 10^5
1 <= N*M <= 10^6
1 <= A[i] <= 10^9
N*M is odd
Input Format
The first and only argument given is the integer matrix A.
Output Format
Return the overall median of the matrix A.
Example Input
Input 1:
A = [ [1, 3, 5],
[2, 6, 9],
[3, 6, 9] ]
Input 2:
A = [ [5, 17, 100] ]
Example Output
Output 1:
5
Output 2:
17
Example Explanation
Explanation 1:
A = [1, 2, 3, 3, 5, 6, 6, 9, 9]
Median is 5. So, we return 5.
Explanation 2:
Median is 17.
*/
/*
Solution Approach
We cannot use extra memory, so we can’t actually store all elements in an array and sort the array.
But since, rows are sorted it must be of some use, right?
Note that in a row you can binary search to find how many elements are smaller than a value X in O(log M).
This is the base of our solution.
Say k = N*M/2. We need to find (k + 1)^th smallest element.
We can use binary search on answer. In O(N log M), we can count how many elements are smaller than X in the matrix.
So, we use binary search on interval [1, INT_MAX]. So, total complexity is O(30 * N log M).
Note:
This problem can be solve by using min-heap, but extra memory is not allowed.
*/
public class Solution {
public int lowerBound(int A[], int val)
{
int l = 0, h = A.length-1, ans = -1;
while(l<=h)
{
int mid = (h-l)/2 + l;
if(A[mid] < val)
{
ans = mid;
l = mid + 1;
}
else
{
h = mid - 1;
}
}
return ans + 1;
}
public int findMedian(int[][] A) {
int low = 0, high = 1000000000, n = A.length, m = A[0].length;
int medPos = n*m/2, ans = -1; // number of elements less than median element
while(low <= high)
{
int mid = (high - low)/2 + low;
int cnt = 0;
//count in each row numer of elements <= mid
for(int i=0;i<n;i++)
{
cnt += lowerBound(A[i], mid);
}
if(cnt > medPos)
{
high = mid - 1;
}
else
{
ans = mid;
low = mid + 1;
}
}
return ans;
}
}