zoukankan      html  css  js  c++  java
  • [LeetCode] 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.

    题意:给一个已经排好序的二维数组,找到第k小的数

    注意,它不是蛇形有序的。

    法一:使用堆,一边插一边删,保证堆只有k个元素就行了;

    class Solution {
        public int kthSmallest(int[][] matrix, int k) {
            int n = matrix.length;
            PriorityQueue<Integer> heap = new PriorityQueue<>(k + 1, (a, b) -> {
                if (a < b)
                    return 1;
                if (a > b)
                    return -1;
                else
                    return 0;
            });
            for (int i = 0; i < n; i++)
                for (int j = 0; j < n; j++) {
                    heap.add(matrix[i][j]);
                    if (heap.size() > k)
                        heap.poll();
                }
            return heap.poll();
        }
    }

    法二:其实用法一有个特点,我们没有利用排好序的这个特点,换言之,随便给个二维数组,就可以实现,显然不可能是最高效的

    既然想到是排好序的,那么又是查,我们就会想到二分的思想

    class Solution {
        private int helper(int[][] matrix, int tar) {
            int n = matrix.length;
            int i = n - 1;
            int j = 0;
            int res = 0;
            while (i >= 0 && j < n) {
                if (matrix[i][j] <= tar) {
                    res += i + 1;
                    j++;
                } else {
                    i--;
                }
            }
            return res;
        }
        public int kthSmallest(int[][] matrix, int k) {
            int n = matrix.length;
            int left = matrix[0][0];
            int right = matrix[n - 1][n - 1];
            while (left < right) {
                int mid = left + (right - left) / 2;
                int cnt = helper(matrix, mid);
                if (cnt < k)
                    left = mid + 1;
                else
                    right = mid;
            }
            return left;
        }
    }
  • 相关阅读:
    论文-Deep Residual Learning for Image Recognition
    网易2017秋招编程题集合-牛客网
    论文-GoogleNet : Going Deeper with Convolutions
    腾讯2016研发工程师编程题-牛客网
    网易2017春招笔试真题编程题集合-牛客网
    剑指offer-把二叉树打印成多行
    剑指offer-翻转单词顺序列
    剑指offer-和为S的连续正数序列
    Java [leetcode 21]Merge Two Sorted Lists
    Java [leetcode 20]Valid Parentheses
  • 原文地址:https://www.cnblogs.com/Moriarty-cx/p/9800363.html
Copyright © 2011-2022 走看看