首页 > 其他分享 >sorted matrix 系列 378

sorted matrix 系列 378

时间:2024-02-19 13:56:05浏览次数:26  
标签:13 matrix int 元素 378 length sorted

 

378. Kth Smallest Element in a Sorted Matrix   Solved Medium   Topics   Companies

Given an n x n matrix where each of the rows and columns is sorted in ascending order, return the kth smallest element in the matrix.

Note that it is the kth smallest element in the sorted order, not the kth distinct element.

You must find a solution with a memory complexity better than O(n2).

Example 1:

Input: matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 8
Output: 13
Explanation: The elements in the matrix are [1,5,9,10,11,12,13,13,15], and the 8th smallest number is 13

Example 2:

Input: matrix = [[-5]], k = 1
Output: -5

Constraints:

  • n == matrix.length == matrix[i].length
  • 1 <= n <= 300
  • -109 <= matrix[i][j] <= 109
  • All the rows and columns of matrix are guaranteed to be sorted in non-decreasing order.
  • 1 <= k <= n2

Follow up:

  • Could you solve the problem with a constant memory (i.e., O(1) memory complexity)?
  • Could you solve the problem in O(n) time complexity? The solution may be too advanced for an interview but you may find reading this paper fun.

解法一:

使用min heap存储每行的头元素,逐个遍历取出k个元素,

将该元素的右侧下一个元素压入heap,最终得到第k个元素

时间复杂度:O(Klog(N))

class Solution { 
    public int kthSmallest(int[][] matrix, int k) {
        int m = matrix.length, n = matrix[0].length, ans = -1; // For general, the matrix need not be a square
        PriorityQueue<int[]> minHeap = new PriorityQueue<>(Comparator.comparingInt(o -> o[0]));
// 每行第一个元素放入heap for (int r = 0; r < Math.min(m, k); ++r) minHeap.offer(new int[]{matrix[r][0], r, 0}); // 开始从heap中取出元素,数k个 for (int i = 1; i <= k; ++i) { int[] top = minHeap.poll();
// 当前元素的位置 int x = top[1], y = top[2]; ans = top[0]; if (y + 1 < n) minHeap.offer(new int[]{matrix[x][y + 1], x, y + 1}); } return ans; } }

解法二:二分猜答案

时间复杂度:O(N) 

class Solution {
    public int kthSmallest(int[][] matrix, int k) {
        // 给定最大/最小值,二分猜答案
        long left = Integer.MIN_VALUE, right = Integer.MAX_VALUE;
        int result = 0;
        while(left <= right) {
            long mid = left + (right - left) / 2;
            // 如果比mid的元素小的个数少于k,那么需要往大了猜
            if(countSmallerOrEqual(matrix, mid) < k) {
                left = mid + 1;
            }
            // 如果比mid元素小的个数多于或者等于k,那么记录下来result,继续往小了猜
            else{
                result = (int)mid;
                right = mid - 1;
            }
        }
        return result;
    }
    private int countSmallerOrEqual(int[][] matrix, long mid) {
        int m = matrix.length, n = matrix[0].length;
        int result = 0;
        // 从右上角开始数
        int x = 0, y = n - 1;
        while(x < m && y >= 0) {
            // 如果比mid大,向左移动
            if(matrix[x][y] > mid) y--;
            // 如果比mid小,向下移动,并且记录当前行小于mid的元素
            else {
                result += y + 1;
                x++;
            }
        }
        return result;
    }
}

 

标签:13,matrix,int,元素,378,length,sorted
From: https://www.cnblogs.com/cynrjy/p/18020936

相关文章

  • 靶机Matrix-Breakout 2 Morpheus
    Matrix-Breakout2Morpheus笔记拿到靶机先扔VMware信息收集没其他东西了,于是先在nmap收集信息nmap-sn192.168.0.0/24-snPing扫描-禁用端口扫描发现靶机地址为192.168.0.104,继续收集信息,先给一套组合拳nmap-T4-sV-p--A192.168.0.104-sV:此选项启用版本检测。......
  • 153. Find Minimum in Rotated Sorted Array
    题目Supposeanarraysortedinascendingorderisrotatedatsomepivotunknowntoyoubeforehand.(i.e., [0,1,2,4,5,6,7] mightbecome [4,5,6,7,0,1,2]).Findtheminelement.Youmayassumenoduplicateexistsinthearray.Example1:Input:[3,4,5,1,2]O......
  • CF1730F Almost Sorted
    更好的阅读体验CF1730FAlmostSorted挺有意思的一道题。刚看到可能有好几种思路,按照\(p\)的大小填\(q\),或者按照下标顺序填等等。试了几次之后考虑按照\(i\)从小到大填入\(q_i\),设\(pos\)为当前填了的最大的\(p_{q_i}\),由于题目的要求,\(1\sim(pos-m-1)\)的所有数......
  • Matrix-Tree 定理
    不会线性代数。行列式定义对一个\(n\timesn\)的矩阵\(A\),其\(n\)阶行列式写作\(\mathrm{det}(A)\)或\(|A|\),定义为\[\mathrm{det}(A)=|A|=\sum_{p}(-1)^{\tau(p)}\prod_{i=1}^{n}a_{i,p_i}\]所有的\(p\)形成\(1\)到\(n\)的全排列,\(\tau(p)\)表示排列\(p\)......
  • MatrixVT:高效View Transformation,让视觉BEV梦想照进现实
    原论文:MatrixVT:EfficientMulti-CameratoBEVTransformationfor3DPerception来自:CVPR2022,旷视科技,Submission-2022.11针对目前BEV中更有优势的Lift-Splat类方法中关键模块(VisionTransformation),MatrixVT实现了非常优雅的优化,在保持模型性能(甚至略微提高)的同时,能大幅降低计......
  • CodeForces 1609G A Stroll Around the Matrix
    洛谷传送门CF传送门我独立做出一道*3000?考虑对于单次询问,除了\(O(nm)\)的dp,有没有什么方法能快速算出答案。发现若\(a_{i+1}-a_i<b_{j+1}-b_j\)则\(i\getsi+1\),否则\(j\getsj+1\)是最优的。这个贪心的证明不难,考虑当前新走到某一行或某一列的贡献......
  • [BZOJ3786] 星系探索 题解
    题目链接:\(BZOJ\)本题通过\(dyf\_DYF\)的题解理解\(ETT\),代码则借鉴\(lcyfrog\)的题解,图片则使用了何太郎的题解。在此笔者感谢这三位神犇。声明变量:\(ls\):左儿子\(rs\):右儿子\(sz\):子树大小\(rk\):对应堆值\(fa\):节点父亲\(sm\):子树权值和\(p\):\(1/-1\)表示第一......
  • AT_arc115_b [ARC115B] Plus Matrix 题解
    AT_arc115_b[ARC115B]PlusMatrix题解题意给定矩阵\(C_{n\timesn}\),求两个数列\(A_n,B_n\),使得\(C_{i,j}=A_i+B_j\)。分析画出一个表格来:213243502131324可以看出来,对于任意一列\(j\),\(C_{*,j}\)都存在有\(B_j\)的贡献。那么我们......
  • SciTech-Math-AdvancedAlgebra-Linear Spaces(Vector Spaces) and Subspace: The Colu
    https://math.mit.edu/~gs/dela/dela_5-1.pdfhttps://people.math.harvard.edu/~knill/teaching/math22b2019/handouts/lecture01.pdfhttps://web.stanford.edu/group/dabmgroup/cgi-bin/dabm/wp-content/uploads/2021/12/Lecture_14.pdfN-elementorderedNumberSequence......
  • Redis - Sorted Set Use Cases
         ......