1 public class Solution { 2 /** 3 * @param nums: an integer array 4 * @param k: An integer 5 * @return: the top k largest numbers in array 6 */ 7 public int[] topk(int[] nums, int k) { 8 // write your code here 9 PriorityQueue pq = new PriorityQueue(); 10 for(int i = 0; i < nums.length; i++){ 11 pq.push(nums[i]); 12 if(pq.size() > k) pq.pop(); 13 } 14 int[] ans = new int[k]; 15 for(int i = k - 1; i >= 0; i--){ 16 ans[i] = pq.top(); 17 pq.pop(); 18 } 19 return ans; 20 } 21 } 22 class PriorityQueue{ 23 ArrayList<Integer> heap = new ArrayList<Integer>(); 24 void push(int num){ 25 heap.add(num); 26 int index = heap.size() - 1; 27 while(index > 0){ 28 int fatherIndex = (index - 1) / 2; 29 if(heap.get(fatherIndex) < heap.get(index)) break; 30 int tempFather = heap.get(fatherIndex); 31 int tempSon = heap.get(index); 32 heap.set(fatherIndex, tempSon); 33 heap.set(index, tempFather); 34 index = fatherIndex; 35 } 36 } 37 int top(){ 38 return heap.get(0); 39 } 40 void pop(){ 41 heap.set(0, heap.get(heap.size() - 1)); 42 heap.remove(heap.size() - 1); 43 int index = 0; 44 while(index < heap.size()){ 45 int index1 = (index + 1) * 2 - 1; 46 int index2 = (index + 1) * 2; 47 int minIndex = index; 48 if(index1 < heap.size() && heap.get(index1) < heap.get(minIndex)) minIndex = index1; 49 if(index2 < heap.size() && heap.get(index2) < heap.get(minIndex)) minIndex = index2; 50 if(minIndex == index) break; 51 int tempFather = heap.get(index); 52 int tempSon = heap.get(minIndex); 53 heap.set(index, tempSon); 54 heap.set(minIndex, tempFather); 55 index = minIndex; 56 } 57 } 58 int size(){ 59 return heap.size(); 60 } 61 }