leetcode练习 Kth Smallest Element in a Sorted Matrix

来源:互联网 发布:如何清除mac桌面图标 编辑:程序博客网 时间:2024/06/06 03:59

依旧对第k大的数耿耿于怀

Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix.

Note that it is the kth smallest element in the sorted order, not the kth distinct element.

Example:

matrix = [   [ 1,  5,  9],   [10, 11, 13],   [12, 13, 15]],k = 8,return 13.

Note:
You may assume k is always valid, 1 ≤ k ≤ n2.

这道题的难点在于每行之间不一定是有序的
因此只能确定左上角和右下角的大小关系
再利用upper_bound的函数,就可以写出速度很快的算法

class Solution {public:    int kthSmallest(vector<vector<int>>& matrix, int k) {        int left = matrix[0][0], right = matrix.back().back();        while (left < right) {            int mid = left + (right - left) / 2, cnt = 0;            for (int i = 0; i < matrix.size(); ++i) {                cnt += upper_bound(matrix[i].begin(), matrix[i].end(), mid) - matrix[i].begin();            }            if (cnt < k) left = mid + 1;            else right = mid;        }        return left;    }};

这里写图片描述

可以说是相当快了

阅读全文
0 0
原创粉丝点击