[leetcode]378. Kth Smallest Element in a Sorted Matrix

[leetcode]378. Kth Smallest Element in a Sorted Matrix


Analysis

今天要吃柚子—— [每天刷题并不难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大的元素,需要注意的是可能存在重复的元素。最简单的办法就是遍历一遍这个矩阵存入数组中,然后排序,输出第k个元素。第二种办法是用堆来实现,因为堆中最大的元素必然排在最前面,所以当堆的大小大于K的时候,就删除堆顶的元素,最后返回堆顶的元素就可以了。

Implement

方法一(数组)

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

方法二(堆)

class Solution {
public:
    int kthSmallest(vector<vector<int>>& matrix, int k) {
        priority_queue<int> q;
        for(int i=0; i<matrix.size(); i++){
            for(int j=0; j<matrix[0].size(); j++){
                q.emplace(matrix[i][j]);
                if(q.size() > k)
                    q.pop();
            }
        }
        return q.top();
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_32135877/article/details/83210860
今日推荐