zoukankan      html  css  js  c++  java
  • Kth Smallest Element in a Sorted Matrix -- LeetCode

    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.

    思路:将第一列的所有数(若数量大于k,则只取前k个数)放入一个数组,构建最小堆。将堆顶的数pop出来,然后将该数所在矩阵的那一行的下一个数放入堆中。该过程进行k-1次。之后堆顶的数就是第k小的数字。因此要判断堆顶的数在矩阵中的位置,因此实际放入堆中的是tuple(值,所在行数,所在列数)。复杂度O(klogm),其中m=min(行数, k)。

     1 class Solution {
     2 public:
     3     int kthSmallest(vector<vector<int>>& matrix, int k) {
     4         //tuple(val, row, col)
     5         vector<tuple<int, int, int> > heap;
     6         for (int i = 0; i < std::min((int)matrix.size(), k); i++)
     7             heap.push_back(make_tuple(matrix[i][0], i, 0));
     8         std::make_heap(heap.begin(), heap.end(), greater<tuple<int, int, int> >());
     9         for (int i = 0; i < k - 1; i++) {
    10             std::pop_heap(heap.begin(), heap.end(), greater<tuple<int, int, int> >());
    11             tuple<int, int, int> top = heap.back();
    12             heap.pop_back();
    13             int row = get<1>(top);
    14             int col = get<2>(top);
    15             if (col < matrix[row].size() - 1)
    16                 heap.push_back(make_tuple(matrix[row][col + 1], row, col + 1));
    17             std::push_heap(heap.begin(), heap.end(), greater<tuple<int, int, int> >());
    18         }
    19         return get<0>(heap.front());
    20     }
    21 };
  • 相关阅读:
    无主之地1
    A+B Problem(V)
    取石子(七)
    又见拦截导弹
    【Chat】实验 -- 实现 C/C++下TCP, 服务器/客户端 "多人聊天室"
    【Echo】实验 -- 实现 C/C++下UDP, 服务器/客户端 通讯
    【Echo】实验 -- 实现 C/C++下TCP, 服务器/客户端 通讯
    对决
    重建二叉树
    花儿朵朵
  • 原文地址:https://www.cnblogs.com/fenshen371/p/5786185.html
Copyright © 2011-2022 走看看