Design a class to find the kth largest element in a stream. Note that it is the kth largest element in the sorted order, not the kth distinct element.
Your KthLargest class will have a constructor which accepts an integer k and an integer array nums, which contains initial elements from the stream. For each call to the method KthLargest.add, return the element representing the kth largest element in the stream.
Example:
int k = 3;
int[] arr = [4,5,8,2];
KthLargest kthLargest = new KthLargest(3, arr);
kthLargest.add(3); // returns 4
kthLargest.add(5); // returns 5
kthLargest.add(10); // returns 5
kthLargest.add(9); // returns 8
kthLargest.add(4); // returns 8
Note:
You may assume that nums’ length ≥ k-1 and k ≥ 1.
题目大意:
设计一个类KthLargest ,它可以存储一组数字,要求能够返回这组数从大到小的第K个数。比如 k = 3; int[] arr = [4,5,8,2]; 排序后是[8,5,4,2],从大到小的第3个数字是4;
通过这道题我想练习一下插入排序及链表,思路如下:
首先在构造方法中,将arr排序,并构造一个双向链表,链表中的每一个节点对应arr中的每一个元素。然后利用插入排序的思想,向链表中添加数字。最后从头扫描链表,返回第K大的数。
import java.util.Arrays;
class KthLargest {
// 链表中的节点
class Node {
Node pre = null;
Node next = null;
int val;
Node(int val) {
this.val = val;
}
}
private int k;
private Node head = new Node(-1);
public KthLargest(int k, int[] nums) {
this.k = k;
Node h = head;
Arrays.sort(nums); // 排序
// 构造链表
for(int i = nums.length-1; i >= 0; i--) {
Node n = new Node(nums[i]);
h.next = n;
n.pre = h;
h = h.next;
}
}
public int add(int val) {
Node h = head.next;
if(h == null) { // 当链表为空时,插入一个头节点
h = new Node(val);
head.next = h;
h.pre = head;
return find();
}
while(h != null) {
if(val > h.val) { // 将节点插入到链表中
Node node = new Node(val);
h.pre.next = node;
node.pre = h.pre;
node.next = h;
h.pre = node;
break;
}
if(h.next == null) { // 将节点插入到链表尾
h.next = new Node(val);
h.next.pre = h;
break;
}
h = h.next;
}
return find();
}
// 找到第K大的数字
private int find() {
int i = 1;
Node h = head.next;
while(i < k && h != null) {
h = h.next;
i++;
}
return h.val;
}
public static void main(String[] args) {
int k = 2;
int[] arr = {0};
KthLargest kthLargest = new KthLargest(k, arr);
System.out.println(kthLargest.add(-1));
System.out.println(kthLargest.add(1));
System.out.println(kthLargest.add(-2));
System.out.println(kthLargest.add(-4));
System.out.println(kthLargest.add(3));
}
}
运行这个小例子,每一步链表中的数字如下:
【0】
【0、-1】
【1、0、-1】
【1、0、-1、-2】
【1、0、-1、-2、-4】
【3、1、0、-1、-2、-4】
输出如下:

293

被折叠的 条评论
为什么被折叠?



