[Question]: Given a row-wise sorted matrix of size r*c, where r is no. of rows and c is no. of columns, find the median in the given matrix. where – r*c is odd
Example 1: Input: r = 3 , c = 3 1 4 9 2 5 6 3 8 7 Output: Median = 5 Explanation: If we find the linear sorted array, the array becomes 1 2 3 4 5 6 7 8 9 So, median = 5 Example 2: Input: r = 3 , c = 3 1 3 8 2 3 4 1 2 5 Output: Median = 3 Explanation: If we find the linear sorted array, the array becomes 1 1 2 2 3 3 4 5 7 8 So, median = 3
// TC:O(row*log col)
// SC:O(1)
func countSmallerThanMid(_ A: [Int], _ mid: Int,_ n: Int) ->Int {
var l = 0, h = n - 1
while l <= h {
var md = (l + h) >> 1
if (A[md] <= mid) {
l = md + 1
} else {
h = md - 1
}
}
return l
}
func findMedian(_ A: [[Int]], _ row: Int, _ col: Int) -> Int {
var low = 1
var high = 1000000000
var n = row
var m = col
while low <= high {
var mid = (low + high) >> 1
var cnt = 0
for i in 0..<n {
cnt += countSmallerThanMid(A[i], mid, col)
}
if (cnt <= (n * m) / 2) {
low = mid + 1
} else {
high = mid - 1
}
}
return low
}
var row1 = 3, col1 = 3
var aMatrix = [[1, 3, 8],
[2, 3, 4],
[1, 2, 5]]
print("The median of the row-wise sorted matrix is: ", findMedian(aMatrix, row1, col1)) // 3
//Explanation: If we find the linear sorted array, the array becomes 1 1 2 2 3 3 4 5 7 8 So, median = 3