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 };
  • 相关阅读:
    dubbo-admin的安装使用
    eclipse生成mybatis的逆向工程-mybatis代码自动生成
    linux7下nenux3.14的maven私服搭建和配置使用
    工具记录及常用查询
    基于RabbitMQ的MQTT协议及应用
    springCloud 之 Eureka服务治理机制及代码运行
    python 的 *args 和 **kwargs
    python with语句
    Python 中下划线
    Python print格式化输出
  • 原文地址:https://www.cnblogs.com/fenshen371/p/5786185.html
Copyright © 2011-2022 走看看