题解 | #寻找第K大#
寻找第K大
https://www.nowcoder.com/practice/e016ad9b7f0b45048c58a9f27ba618bf
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param a int整型一维数组 * @param n int整型 * @param K int整型 * @return int整型 */ public int findKth (int[] a, int n, int K) { // write code here // 方法一:冒泡排序后取第K个数的值即可 // this.bubbleSort(a); // return a[n-K]; // 方法一:使用PriorityQueue优先级队列进行自动大根堆排序,然后从对头poll出第K个数即可 Queue<Integer> que = new PriorityQueue<Integer>((o1,o2) -> { return o2.compareTo(o1); }); for(int i=0;i<n;i++) { que.add(a[i]); } for(int i=0;i<K-1;i++) { que.poll(); } return que.poll(); } public void bubbleSort(int[] input) { for(int i=0;i<input.length-1;i++) { for(int j=i+1;j<input.length;j++) { if(input[i] > input[j]) { int tmp = input[i]; input[i] = input[j]; input[j] = tmp; } } } } public void printArr(int[] input) { for(int i=0;i<input.length;i++) { System.out.print(input[i] + ","); } System.out.println(); } }