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)
  • 相关阅读:
    刷题94—树(一)
    刷题93—动态规划(十)
    刷题92—动态规划(九)
    刷题91—动态规划(八)
    android Q build 变化
    ubuntu下解压rar文件
    Android PAI (PlayAutoInstall)预装APK 功能
    MTK Android O1平台预置apk
    预置第三方apk到MTK项目相关问题总结
    Android预置Apk方法
  • 原文地址:https://www.cnblogs.com/h-hkai/p/9908433.html
Copyright © 2011-2022 走看看