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.
matrix = [ [ 1, 5, 9], [10, 11, 13], [12, 13, 15] ], k = 8, return 13
public class Solution { public int kthSmallest(int[][] matrix, int k) { PriorityQueuepq = new PriorityQueue<>(new Comparator (){ public int compare(int[] a, int[] b){ return a[2] - b[2]; } }); int n = matrix.length; // add first row for(int i=0; i< n; i++){ pq.offer(new int[]{0, i, matrix[0][i]}); } for(int i=0; i public class Solution { public int kthSmallest(int[][] matrix, int k) { int m = matrix.length, n = matrix[0].length; int lo = matrix[0][0], hi = matrix[m-1][n-1]; while(lo < hi){ int mid = lo + (hi-lo)/2; int count = 0, j = n -1; for(int i=0; i=0 && matrix[i][j] > mid) j--; // count those <= mid count += j+1; } // if count < k, the number is smaller if(count < k) lo = mid+1; else hi = mid; } return lo; }
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://specialneedsforspecialkids.com/yun/67070.html
摘要:先放一行,或一列把堆頂?shù)淖钚≡厝〕鰜恚〈危绻撚邢乱恍邢乱涣械模湃攵阎凶钚〉膫€元素已經(jīng)在上面的循環(huán)被完了,下一個堆頂元素就是 Problem Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in...
摘要:復雜度是,其中。這做法和異曲同工。看了網(wǎng)上給的解法,沒有二分,二分的是結(jié)果。每次找到一個,然后求比它小的元素的個數(shù),根據(jù)個數(shù)大于還是小于來二分。參考算的時候可以優(yōu)化 378. Kth Smallest Element in a Sorted Matrix 題目鏈接:https://leetcode.com/problems... 求矩陣里面第k小的數(shù),首先比較容易想到的是用heap來做...
摘要:因此我們可以采用部分元素堆排序即可。即我們每次只需要可能構(gòu)成第個元素的值進行堆排序就可以了。 題目要求 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...
Problem Find the kth smallest number in at row and column sorted matrix. Example Given k = 4 and a matrix: [ [1 ,5 ,7], [3 ,7 ,8], [4 ,8 ,9], ] return 5 Challenge O(k log n), n is the maximal n...
摘要:中序遍歷復雜度時間空間思路因為左節(jié)點小于根節(jié)點小于右節(jié)點,二叉搜索樹的一個特性就是中序遍歷的結(jié)果就是樹內(nèi)節(jié)點從小到大順序輸出的結(jié)果。這里采用迭代形式,我們就可以在找到第小節(jié)點時馬上退出。這樣我們就可以用二叉樹搜索的方法來解決這個問題了。 Kth Smallest Element in a BST Given a binary search tree, write a function...
閱讀 3713·2021-10-12 10:11
閱讀 1980·2019-08-30 15:53
閱讀 1589·2019-08-30 13:15
閱讀 2303·2019-08-30 11:25
閱讀 1798·2019-08-29 11:24
閱讀 1648·2019-08-26 13:53
閱讀 3522·2019-08-26 13:22
閱讀 1747·2019-08-26 10:24