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 };
  • 相关阅读:
    推荐]历史上最强的绕口令
    超级经理人的关系学:打造黄金人脉
    个人创业的难点和解决之道
    你的人脉关系中不可缺少的十种人[推荐]
    哲理短文一则:揭示最好的成功法则
    [经验交流]太精彩,太有启发性了(经典经典) 转
    权力领域是人才浪费的致命区域
    2006创业完全手册
    爱你我的宝贝(转)
    最远的你是我最近的爱
  • 原文地址:https://www.cnblogs.com/fenshen371/p/5786185.html
Copyright © 2011-2022 走看看