列表

详情


2387. 行排序矩阵的中位数

给定一个包含 奇数 个整数的 m x n 矩阵 grid,其中每一行按 非递减 的顺序排序,返回矩阵的 中位数

你必须以 O(m * log(n)) 的时间复杂度来解决这个问题。

 

示例 1:

输入: grid = [[1,1,2],[2,3,3],[1,3,4]]
输出: 2
解释: 矩阵的元素按顺序排列为 1,1,1,2,2,3,3,3,4。中位数是 2。

示例 2:

输入: grid = [[1,1,3,3,4]]
输出: 3
解释: 矩阵的元素按顺序排列为 1,1,3,3,4。中位数是 3。

 

提示:

原站题解

去查看

上次编辑到这里,代码来自缓存 点击恢复默认模板
class Solution { public: int matrixMedian(vector<vector<int>>& grid) { } };

java 解法, 执行用时: 78 ms, 内存消耗: 64.9 MB, 提交时间: 2023-10-16 22:03:13

class Solution {
    public int matrixMedian(int[][] grid) {
        int m = grid.length;
        int n = grid[0].length;
        Queue<int[]> q = new PriorityQueue<>(new Comparator<int[]>() {

            @Override
            public int compare(int[] o1, int[] o2) {
                return Integer.compare(grid[o1[0]][o1[1]], grid[o2[0]][o2[1]]);
            }

        });

        for (int i = 0; i < m; ++i) {
            q.offer(new int[] { i, 0 });
        }
        int cur = 0;
        while (!q.isEmpty()) {
            int[] p = q.poll();
            int x = p[0];
            int y = p[1];

            if (cur == m * n / 2) {
                return grid[x][y];
            }
            if (++y < n) {
                q.offer(new int[] { x, y });
            }
            ++cur;
        }
        return -1;

    }
}

cpp 解法, 执行用时: 112 ms, 内存消耗: 34.7 MB, 提交时间: 2023-10-16 22:02:39

class Solution {
public:
    bool check(int x, int target, vector<vector<int>>& grid) {
        int cnt = 0;
        for (auto &row : grid) {
            cnt += lower_bound(row.begin(), row.end(), x) - row.begin();
        }
        return cnt <= target;
    }

    int matrixMedian(vector<vector<int>>& grid) {
        int m = grid.size(), n = grid[0].size();
        int target = m * n / 2;

        int left = 1e6, right = 1;
        for (auto &row : grid) {
            left = min(left, row.front());
            right = max(right, row.back());
        }
        
        int ans = left;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (check(mid, target, grid)) {
                left = mid + 1;
                ans = mid;
            } else {
                right = mid - 1;
            }
        }
        return ans;
    }
};

python3 解法, 执行用时: 84 ms, 内存消耗: 45.9 MB, 提交时间: 2023-10-16 22:02:26

class Solution:
    def matrixMedian(self, grid: List[List[int]]) -> int:
        m, n = len(grid), len(grid[0])

        def check(x: int) -> bool:
            cnt = 0
            for row in grid:
                cnt += bisect_left(row, x)
            return cnt <= m * n // 2
        
        left = min(row[0] for row in grid)
        right = max(row[-1] for row in grid)
        ans = left
        while left <= right:
            mid = (left + right) // 2
            if check(mid):
                left = mid + 1
                ans = mid
            else:
                right = mid - 1
        return ans

上一题