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)
  • 相关阅读:
    R 多图间距调整
    ggplot2 颜色渐变(离散颜色)设置
    R语言因子排序
    利用plink软件基于LD信息过滤SNP
    利用vcftools比较两个vcf文件
    在R语言中使用Stringr进行字符串操作
    perl 数组快速去除重复元素
    Shell中 ##%% 操作变量名
    Java基础之数值类型之间的转换
    Java中0.2减0.1 结果为什么不是0.1?
  • 原文地址:https://www.cnblogs.com/h-hkai/p/9908433.html
Copyright © 2011-2022 走看看