首页 > 其他 > 详细

LeetCode-378 Kth Smallest Element in a Sorted Matrix

时间:2019-07-29 14:15:12      阅读:91      评论:0      收藏:0      [点我收藏+]

题目描述

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.

 

题目大意

在一个整数矩阵中,按行有序排列,列有序排列,要求找出矩阵中第k小的数字。

 

示例

E1

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

return 13.

 

解题思路

简单利用multiset就可以解决本问题,可以使用二分对每一行进行搜索以减少时间复杂度。

 

复杂度分析

时间复杂度:O(N2 * log(N2))

空间复杂度:O(N2)

 

代码

class Solution {
public:
    int kthSmallest(vector<vector<int>>& matrix, int k) {
        multiset<int> seq;
        if(matrix.size() == 0 || matrix[0].size() == 0)
            return 0;
        
        for(int i = 0; i < matrix.size(); ++i)
            for(int j = 0; j < matrix[i].size(); ++j)
                seq.insert(matrix[i][j]);
        
        auto it = seq.begin();
        for(int i = 1; i < k; ++i) {
            ++it;
        }
        return *it;
    }
};

 

LeetCode-378 Kth Smallest Element in a Sorted Matrix

原文:https://www.cnblogs.com/heyn1/p/11262770.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!