Problem
Find the kth smallest number in at row and column sorted matrix.
ExampleGiven k = 4 and a matrix:
[ [1 ,5 ,7], [3 ,7 ,8], [4 ,8 ,9], ]
return 5
ChallengeO(k log n), n is the maximal number in width and height.
Note SolutionI. Muggle (95% ac, last case exceeded time limit)
public class Solution { public int kthSmallest(int[][] matrix, int k) { int size = matrix.length * matrix[0].length; if (matrix == null) return 0; PriorityQueuequeue = new PriorityQueue (size+1); for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) { queue.add(matrix[i][j]); } } for (int i = 1; i < k; i++) { queue.remove(); } return queue.peek(); } }
II. 堆排序
public class Solution { public int kthSmallest(final int[][] matrix, int k) { boolean[][] visited = new boolean[matrix.length][matrix[0].length]; PriorityQueueheap = new PriorityQueue (k, new Comparator (){ public int compare(int[] a, int[] b) { return Integer.compare(matrix[a[0]][a[1]], matrix[b[0]][b[1]]); } }); heap.add(new int[]{0,0}); visited[0][0] = true; while (k > 1) { int[] res = heap.remove(); int x = res[0]; int y = res[1]; if (x+1 < matrix.length && visited[x+1][y] == false) { visited[x+1][y] = true; heap.add(new int[]{x+1, y}); } if (y+1 < matrix[0].length && visited[x][y+1] == false) { visited[x][y+1] = true; heap.add(new int[]{x, y+1}); } k--; } int[] res = heap.remove(); return matrix[res[0]][res[1]]; } }
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://specialneedsforspecialkids.com/yun/65991.html
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...
摘要:先放一行,或一列把堆頂?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...
摘要:復(fù)雜度是,其中。這做法和異曲同工。看了網(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...
摘要:解題思路本題需要找的是第小的節(jié)點值,而二叉搜索樹的中序遍歷正好是數(shù)值從小到大排序的,那么這題就和中序遍歷一個情況。 Kth Smallest Element in a BSTGiven a binary search tree, write a function kthSmallest to find the kth smallest element in it. Note: You ...
閱讀 3526·2021-09-27 13:35
閱讀 3563·2019-08-29 17:09
閱讀 2433·2019-08-26 11:30
閱讀 706·2019-08-26 10:32
閱讀 539·2019-08-26 10:23
閱讀 1200·2019-08-26 10:20
閱讀 3156·2019-08-23 15:26
閱讀 3562·2019-08-23 14:33