zoukankan      html  css  js  c++  java
  • 378. 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.

    Approach #1: restore the matrix into a one-deminsional array, then sort

    class Solution {
    public:
        int kthSmallest(vector<vector<int>>& matrix, int k) {
            vector<int> s;
            int row = matrix.size();
            int col = matrix[0].size();
            for (int i = 0; i < row; ++i) {
                for (int j = 0; j < col; ++j) {
                    s.push_back(matrix[i][j]);
                }
            }
            sort(s.begin(), s.end());
            return s[k-1];
        }
    };
    
    85 / 85 test cases passed.
    Status: 

    Accepted

    Runtime: 32 ms
    Submitted: 1 hour, 59 minutes ago

    Approach #2: Using Bianry Search in two-deminsional array.

    class Solution {
    public:
        int kthSmallest(vector<vector<int>>& matrix, int k) {
            int row = matrix.size();
            int col = matrix[0].size();
            int l = matrix[0][0];
            int r = matrix[row-1][col-1];
            while (l < r) {
                int m = l + (r - l) / 2;
                int num = 0;
                for (int i = 0; i < row; ++i) {
                    int pos = upper_bound(matrix[i].begin(), matrix[i].end(), m) - matrix[i].begin();
                    num += pos;
                }
                if (num < k) l = m + 1;
                else r = m;
            }
            return l;
        }
    };
    

    Runtime: 36 ms, faster than 44.09% of C++ online submissions for Kth Smallest Element in a Sorted Matrix.

    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    组合模式
    MySQL8.0 下载安装启动(Windows10)
    OI如逆旅,我亦是行人——省选
    闲话—江湖痴情浅,信步余生。平剑红烛,青丝微绾,却话奁中。
    此时彼方
    CSP 2019游记 & 退役记
    西狂 杨过
    SDOI 2019 Round1 游记
    NOIP2018游记
    未来可期,不知所终
  • 原文地址:https://www.cnblogs.com/h-hkai/p/9908433.html
Copyright © 2011-2022 走看看