劍指 offer之最小的K個數_Java

題目:最小的K個數

題目描述
輸入n個整數,找出其中最小的K個數。例如輸入4,5,1,6,2,7,3,8這8個數字,則最小的4個數字是1,2,3,4,。

解題思路:
維護一個大小爲k的大頂堆,當數組中多於k的部分分別與大頂堆的堆頂元素進行比較,如果大於堆頂元素,將堆頂元素推出去,將比堆頂元素小的這個數放進這個大小爲k的大頂堆中,不斷循環比較,直到數組中沒有元素爲止。
ps:沒有自己實現大頂堆,而是直接使用Java中提供的API PriorityQueue

代碼實現:

import java.util.*;
public class Solution {
    public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
    //存放結果集
        ArrayList<Integer> res=new ArrayList<>();
		int len=input.length;
		//代碼的魯棒性
		if(k>len || k<=0) {
			return res;
		}
		//維護一個大頂堆
		PriorityQueue<Integer> queue = new PriorityQueue<Integer>(k,new Comparator<Integer>() {
			@Override
			public int compare(Integer o1, Integer o2) {
				//前面的大於後面的
				return o2.compareTo(o1);
			}
		});
		for(int i=0;i<len;i++) {
			if(i<k) {
				//當queue的個數小於k時,說明大頂堆的個數還不夠
				queue.add(input[i]);
			}else {
				//到了大頂堆的個數時,與堆頂元素進行比較
				if(queue.peek()>input[i]) {
					queue.poll();//堆頂元素推出去
					queue.add(input[i]);//該元素加進去
				}
			}
		}
		//將結果壓入到結果集中
		for(Integer que:queue) {
			res.add(que);
		}
		return res;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章