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)
  • 相关阅读:
    redux-devtools的使用
    Electron-builder打包详解
    HTML JAVASCRIPT CSS 大小写敏感问题
    electron/nodejs实现调用golang函数
    基于react开发package.json的配置
    Chrome插件(扩展)开发全攻略
    Chrome插件中 popup,background,contentscript消息传递机制
    Linux 开机引导和启动过程详解
    bash 的配置文件加载顺序
    常用Electron App打包工具
  • 原文地址:https://www.cnblogs.com/h-hkai/p/9908433.html
Copyright © 2011-2022 走看看