703.数据流中的第K大元素
思路1:
利用数组扩容并排序,最后返回即可
代码实现
class KthLargest {
int k;
int[] nums;
public KthLargest(int k, int[] nums) {
this.k = k;
this.nums = nums;
}
public int add(int val) {
int[] newNums = new int[nums.length + 1];
for (int i = 0; i < nums.length; i++) {
newNums[i] = nums[i];
}
newNums[newNums.length - 1] = val;
nums = newNums;
Arrays.sort(nums);
return nums[nums.length - k];
}
}
/**
* Your KthLargest object will be instantiated and called as such:
* KthLargest obj = new KthLargest(k, nums);
* int param_1 = obj.add(val);
*/
思路2:
利用优先级队列完成
代码实现
class KthLargest {
PriorityQueue<Integer> queue = new PriorityQueue<Integer>();
int k;
public KthLargest(int k, int[] nums) {
this.k = k;
for (int x : nums) {
add(x);
}
}
public int add(int val) {
queue.add(val);
if (queue.size() > k) {
queue.poll();
}
return queue.peek();
}
}
/**
* Your KthLargest object will be instantiated and called as such:
* KthLargest obj = new KthLargest(k, nums);
* int param_1 = obj.add(val);
*/