設計一個高效算法,算出隨機數組裏的中位數

解題思路:

  1. 通過最大堆、最小堆來實現實時中位數的獲取。
  2. 最大堆中存放比最小堆小的元素。
  3. 如果最大堆的對頭元素大於最小堆,則進行交換。
  4. 偶數下標的元素存入最小堆,奇數下標的元素存入最大堆

 

public class Median {
    public int[] getMedian(int[] A, int n) {
        int[] res = new int[A.length];

        
        Comparator<Integer> comparator = new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o2 - o1;
            }
        };
		// 最大堆
        PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>(n, comparator);
        // 最小堆
        PriorityQueue<Integer> minHeap = new PriorityQueue<Integer>(n);

        for (int i = 0; i < n; i++) {
            if (i % 2 == 0) {
                // 存入最小堆前判斷當前元素是否小於最大堆的堆頂元素
                if (!maxHeap.isEmpty() && A[i] < maxHeap.peek()) {
					//刪除最大堆中的頭元素,然後添加到最小堆裏
                    minHeap.offer(maxHeap.poll());
                    maxHeap.offer(A[i]);
                } else {
                    minHeap.offer(A[i]);
                }
				//獲取頭元素
                res[i] = minHeap.peek();
            } else {
                // 存入最大堆之前判斷當前元素是否大於最小堆的堆頂元素
                if (!minHeap.isEmpty() && A[i] > minHeap.peek()) {
                    maxHeap.offer(minHeap.poll());
                    minHeap.offer(A[i]);
                } else {
                    maxHeap.offer(A[i]);
                }
                res[i] = maxHeap.peek();
            }
        }

        return res;
    }
}

 

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