#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 客啦 拖了一个半月 这道题一定有时间复杂度再低一点的解法但是暂时没想到

[年前每日一问: 今天我的粉丝到 10 个了么?]

FHFHFH

原文地址:https://www.cnblogs.com/zlrrrr/p/10339788.html