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)
  • 相关阅读:
    Mathematica 计算矩阵的伴随矩阵
    教你如何在word中像LaTex那样打出漂亮的数学公式
    中国科学院大学2016年硕转博考试试题
    161024解答
    161023解答
    161020-1解答
    关于查询扩展版ESI高被引论文的说明
    [Tex学习笔记]让项目编号从4开始
    [Tex学习]WinEdit 常用软件快捷键
    最著名的数学家一般也是最著名的力学家
  • 原文地址:https://www.cnblogs.com/h-hkai/p/9908433.html
Copyright © 2011-2022 走看看