码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2019-01-30 21:45:57      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:may   sum   ali   ted   cpp   http   turn   font   vector   

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

标签:may   sum   ali   ted   cpp   http   turn   font   vector   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!