LeetCode 2387. Median of a Row Wise Sorted Matrix Solution in Java, C++, Python & Go | Explanation + Code

CoderIndeed
0
2387. Median of a Row Wise Sorted Matrix

Description

Given an m x n matrix grid containing an odd number of integers where each row is sorted in non-decreasing order, return the median of the matrix.

You must solve the problem in less than O(m * n) time complexity.

 

Example 1:

Input: grid = [[1,1,2],[2,3,3],[1,3,4]]
Output: 2
Explanation: The elements of the matrix in sorted order are 1,1,1,2,2,3,3,3,4. The median is 2.

Example 2:

Input: grid = [[1,1,3,3,4]]
Output: 3
Explanation: The elements of the matrix in sorted order are 1,1,3,3,4. The median is 3.

 

Constraints:

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 500
  • m and n are both odd.
  • 1 <= grid[i][j] <= 106
  • grid[i] is sorted in non-decreasing order.

Solutions

Solution 1: Two Binary Searches

The median is actually the target = \left \lceil m × n2 \right \rceil-th number after sorting.

We perform a binary search on the elements of the matrix x, counting the number of elements in the grid that are greater than x, denoted as cnt. If cnt \ge target, it means the median is on the left side of x (including x); otherwise, it is on the right side.

The time complexity is O(m × log n × log M), where m and n are the number of rows and columns of the grid, respectively, and M is the maximum element in the grid. The space complexity is O(1).

PythonJavaC++Go
class Solution: def matrixMedian(self, grid: List[List[int]]) -> int: def count(x): return sum(bisect_right(row, x) for row in grid) m, n = len(grid), len(grid[0]) target = (m * n + 1) >> 1 return bisect_left(range(10**6 + 1), target, key=count)(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !