#Leetcode# 378. Kth Smallest Element in a Sorted Matrix

Posted 丧心病狂工科女

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了#Leetcode# 378. Kth Smallest Element in a Sorted Matrix相关的知识,希望对你有一定的参考价值。

https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/

 

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.

代码:

class Solution {
public:
    int kthSmallest(vector<vector<int>>& matrix, int k) {
        int n = matrix.size();
        
        vector<int> ans;
        for(int i = 0; i < n; i ++) {
            for(int j = 0; j < n; j ++)
                ans.push_back(matrix[i][j]);
        }
        sort(ans.begin(), ans.end());
        return ans[k - 1];
    }
};

  600篇 Be 客啦 拖了一个半月 这道题一定有时间复杂度再低一点的解法但是暂时没想到

FHFHFH


以上是关于#Leetcode# 378. Kth Smallest Element in a Sorted Matrix的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 378. Kth Smallest Element in a Sorted Matrix

Leetcode378. Kth Smallest Element in a Sorted Matrix

LeetCode 378: Kth Smallest Element in Sorted Matrix

Leetcode:378. Kth Smallest Element in a Sorted Matrix

leetcode 378. Kth Smallest Element in a Sorted Matrix

378. Kth Smallest Element in a Sorted Matrix