四種方法花式吊打面試題目——最小k個數

最小K個數

算法題目:

​ 輸入一個整數數組arr,找出其中最小的k個數。

思路

​ 比較直觀的想法就是將整個數組排序,然後輸出前K小的數,所以我們使用目前最高效的排序算法,快排來解決問題。所以所需的時間複雜度O(nlogn)。但是由於取前K個數所以快排不用完全執行。

快排思想

​ 直接通過快排切分好第K小的數(下標k-1)

大根堆(前K小)/小根堆(前K大)

  • 因爲java中有現成的PriorityQueue,實現起來簡單O(NlogK)

​ 是因爲求前k小,所以用一個容量爲K的大根堆,每次poll出最大的數,那堆中保留就是前K小

​ 這個方法雖然比較慢(比快排)但是由於有現成的 PriorityQueue(默認小根堆)

二叉搜索樹

  • 好處是求得的前K大的數字是有序的
  • 因爲存在重複數字,所以使用TreeMap而不是TreeSet
  • Tree的key是數字,value是該數字的個數

我們遍歷數組中的數組,維護一個數字總個數爲K的TreeMap

  • 若目前map中的數字個數小於K,則將map中當前數字對應的個數+1
  • 否則,判斷當前數字與map中最大數字的大小關係
    • 大於等於最大數字則直接跳過
    • 否則將map中對應數字的個數+1,並將map中最大數字對應的個數-1

當有數據範圍時直接計數排序

代碼實現

快排思想

class Solution {
    public int[] getLeastNumbers(int[] arr, int k) {
        if (k == 0 || arr.length == 0) {
            return new int[0];
        }
        // 最後一個參數表示我們要找的是下標爲k-1的數
        return quickSearch(arr, 0, arr.length - 1, k - 1);
    }

    private int[] quickSearch(int[] nums, int lo, int hi, int k) {
        // 每快排切分1次,找到排序後下標爲j的元素,如果j恰好等於k就返回j以及j左邊所有的數;
        int j = partition(nums, lo, hi);
        if (j == k) {
            return Arrays.copyOf(nums, j + 1);
        }
        // 否則根據下標j與k的大小關係來決定繼續切分左段還是右段。
        return j > k? quickSearch(nums, lo, j - 1, k): quickSearch(nums, j + 1, hi, k);
    }

    // 快排切分,返回下標j,使得比nums[j]小的數都在j的左邊,比nums[j]大的數都在j的右邊。
    private int partition(int[] nums, int lo, int hi) {
        int v = nums[lo];
        int i = lo, j = hi + 1;
        while (true) {
            while (++i <= hi && nums[i] < v);
            while (--j >= lo && nums[j] > v);
            if (i >= j) {
                break;
            }
            int t = nums[j];
            nums[j] = nums[i];
            nums[i] = t;
        }
        nums[lo] = nums[j];
        nums[j] = v;
        return j;
    }
}

大根堆

// 保持堆的大小爲K,然後遍歷數組中的數字,遍歷的時候做如下判斷:
// 1. 若目前堆的大小小於K,將當前數字放入堆中。
// 2. 否則判斷當前數字與大根堆堆頂元素的大小關係,如果當前數字比大根堆堆頂還大,這個數就直接跳過;
//    反之如果當前數字比大根堆堆頂小,先poll掉堆頂,再將該數字放入堆中。
class Solution {
    public int[] getLeastNumbers(int[] arr, int k) {
        if (k == 0 || arr.length == 0) {
            return new int[0];
        }
        // 默認是小根堆,實現大根堆需要重寫一下比較器。
        Queue<Integer> pq = new PriorityQueue<>((v1, v2) -> v2 - v1);
        for (int num: arr) {
            if (pq.size() < k) {
                pq.offer(num);
            } else if (num < pq.peek()) {
                pq.poll();
                pq.offer(num);
            }
        }
        
        // 返回堆中的元素
        int[] res = new int[pq.size()];
        int idx = 0;
        for(int num: pq) {
            res[idx++] = num;
        }
        return res;
    }
}

二叉搜索樹

class Solution {
    public int[] getLeastNumbers(int[] arr, int k) {
        if (k == 0 || arr.length == 0) {
            return new int[0];
        }
        // TreeMap的key是數字, value是該數字的個數。
        // cnt表示當前map總共存了多少個數字。
        TreeMap<Integer, Integer> map = new TreeMap<>();
        int cnt = 0;
        for (int num: arr) {
            // 1. 遍歷數組,若當前map中的數字個數小於k,則map中當前數字對應個數+1
            if (cnt < k) {
                map.put(num, map.getOrDefault(num, 0) + 1);
                cnt++;
                continue;
            } 
            // 2. 否則,取出map中最大的Key(即最大的數字), 判斷當前數字與map中最大數字的大小關係:
            //    若當前數字比map中最大的數字還大,就直接忽略;
            //    若當前數字比map中最大的數字小,則將當前數字加入map中,並將map中的最大數字的個數-1。
            Map.Entry<Integer, Integer> entry = map.lastEntry();
            if (entry.getKey() > num) {
                map.put(num, map.getOrDefault(num, 0) + 1);
                if (entry.getValue() == 1) {
                    map.pollLastEntry();
                } else {
                    map.put(entry.getKey(), entry.getValue() - 1);
                }
            }
            
        }

        // 最後返回map中的元素
        int[] res = new int[k];
        int idx = 0;
        for (Map.Entry<Integer, Integer> entry: map.entrySet()) {
            int freq = entry.getValue();
            while (freq-- > 0) {
                res[idx++] = entry.getKey();
            }
        }
        return res;
    }
}

計數排序(有數據範圍)

class Solution {
    public int[] getLeastNumbers(int[] arr, int k) {
        if (k == 0 || arr.length == 0) {
            return new int[0];
        }
        // 統計每個數字出現的次數
        int[] counter = new int[10001];
        for (int num: arr) {
            counter[num]++;
        }
        // 根據counter數組從頭找出k個數作爲返回結果
        int[] res = new int[k];
        int idx = 0;
        for (int num = 0; num < counter.length; num++) {
            while (counter[num]-- > 0 && idx < k) {
                res[idx++] = num;
            }
            if (idx == k) {
                break;
            }
        }
        return res;
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章