1. 程式人生 > >找第k大的專題: 378. Kth Smallest Element in a Sorted Matrix && 230. Kth Smallest Element in a BST

找第k大的專題: 378. Kth Smallest Element in a Sorted Matrix && 230. Kth Smallest Element in a BST

找第k大的專題

378. Kth Smallest Element in a Sorted Matrix

1. 題目描述
題目連結

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.

2. 題目分析
同一行中,從左到右是升序,同一列中,從上到下是升序,但有個坑,就是不保證上一行的結尾的數值會比下一行的第一個數值小,所以說到底對於找第k小的值這二維陣列是沒有規律的。

3. 解決思路
那麼如果我們要找第k小的值,那麼肯定是需要排序的。排序可以使用堆排序找到第k小的值,或者直接呼叫java中的陣列排序API,即Arrays.sort(array);

4. 程式碼實現(java)

  • 堆排序,可以使用優先佇列,會自動進行堆排序
public static int kthSmallest(int[][] matrix, int k) {
        if (matrix == null){
            return 0;
        }
        PriorityQueue<Integer> priorityQueue =new PriorityQueue<Integer>(matrix.length * matrix.length);
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix.length; j++) {
                priorityQueue.add(matrix[i][j]);
            }
        }
        int count = 0;
        while (!priorityQueue.isEmpty()){
            int value = priorityQueue.poll();
            count++;
            if (count == k){
                return value;
            }
        }
        return 0;
    }
  • Arrays.sort(array)排序
public static int kthSmallest(int[][] matrix, int k) {
        if (matrix == null){
            return 0;
        }
        int[] dp = new int[matrix.length * matrix.length];
        int index = 0;
        for(int i=0; i<matrix.length; i++) {
            for(int j=0; j<matrix.length; j++) {
                dp[index] = matrix[i][j];
                index++;
            }
        }
        Arrays.sort(dp);
        return dp[k-1];
    }

230. Kth Smallest Element in a BST

1. 題目描述
題目連結

Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.
Note:
You may assume k is always valid, 1 ≤ k ≤ BST’s total elements.
Example 1:
Input: root = [3,1,4,null,2], k = 1
3
/
1 4

2
Output: 1
Example 2:
Input: root = [5,3,6,2,4,null,null,1], k = 3
5
/
3 6
/
2 4
/
1
Output: 3
Follow up:
What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine?

2. 題目分析
從二叉搜尋樹中找第k小的值,要找第k小的值,那麼肯定要排序,我們知道,二叉搜尋樹的中序遍歷就是有序列表了,所以我們只要對BST進行中序遍歷就行了。
中序遍歷的方式有兩種:遞迴、非遞迴(棧)

3. 程式碼實現(java)
這裡就不分析程式碼過程了,如果對BST三種遍歷不瞭解的,可以檢視我的部落格:
145. 二叉樹的後序遍歷145. 二叉樹的中序遍歷145. 二叉樹的先序遍歷

/**
     * 230. Kth Smallest Element in a BST
     * @param root
     * @param k
     * @return
     */
    public int kthSmallest(TreeNode root, int k) {
        if (root == null){
            return 0;
        }
        int count = 0;
        Stack<TreeNode> stack = new Stack<TreeNode>();
        TreeNode node = root;
        while (node != null || !stack.isEmpty()){
            //找到最左葉子節點
            if (node != null){
                stack.push(node);
                node = node.left;
            }else{
                node = stack.pop();
                count++;
                System.out.println("節點值為:"+node.val);
                if (count == k){
                    return node.val;
                }
                node = node.right;
            }
        }
        return 0;
    }