Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
Example 1:
Input: [3,2,1,5,6,4]
and k = 2
Output: 5
Example 2:
Input: [3,2,3,1,2,4,5,5,6]
and k = 4
Output: 4
Note:
You may assume k is always valid, 1 ≤ k ≤ array's length.
class Solution { public int findKthLargest(int[] nums, int k) { ArrayList<Integer> list = new ArrayList(); for(int i: nums){ list.add(i); } Collections.sort(list); Collections.reverse(list); return list.get(k-1); } }
有很多种解法,最先想到的是存到arraylist里再调用api。
class Solution { public int findKthLargest(int[] nums, int k) { final Queue<Integer> q = new PriorityQueue<>(); for (int x : nums) { if (q.size() < k) { q.offer(x); } else { final int top = q.peek(); if (x > top) { q.poll(); q.offer(x); } } } return q.peek(); } }
priorityqueue:压入随机数,按从小到大输出。设置一个长为k的队列,然后把比最大数和第二大数存入,再peek就是答案,太巧妙了