import
java.util.PriorityQueue;
class
ListNode {
int
val;
ListNode next;
public
ListNode(
int
x) {
val = x;
next =
null
;
}
}
public
class
TribonacciLinkedList {
public
static
int
findKthLargestTribonacci(ListNode head,
int
K) {
PriorityQueue<Integer> minHeap =
new
PriorityQueue<>();
java.util.function.Predicate<Integer> isTribonacci = num -> {
int
a =
0
, b =
1
, c =
1
;
while
(c <= num) {
if
(c == num) {
return
true
;
}
int
temp = a + b + c;
a = b;
b = c;
c = temp;
}
return
false
;
};
ListNode current = head;
while
(current !=
null
) {
if
(isTribonacci.test(current.val)) {
minHeap.add(current.val);
if
(minHeap.size() > K) {
minHeap.poll();
}
}
current = current.next;
}
return
minHeap.peek();
}
public
static
void
main(String[] args) {
ListNode head1 =
new
ListNode(
12
);
head1.next =
new
ListNode(
4
);
head1.next.next =
new
ListNode(
9
);
head1.next.next.next =
new
ListNode(
3
);
head1.next.next.next.next =
new
ListNode(
0
);
head1.next.next.next.next.next =
new
ListNode(
25
);
head1.next.next.next.next.next.next =
new
ListNode(
13
);
int
K1 =
2
;
int
result1 = findKthLargestTribonacci(head1, K1);
System.out.println(
"The "
+ K1 +
"th largest Tribonacci number is: "
+ result1);
ListNode head2 =
new
ListNode(
144
);
head2.next =
new
ListNode(
111
);
head2.next.next =
new
ListNode(
44
);
head2.next.next.next =
new
ListNode(
81
);
head2.next.next.next.next =
new
ListNode(
1
);
head2.next.next.next.next.next =
new
ListNode(
15
);
head2.next.next.next.next.next.next =
new
ListNode(
149
);
head2.next.next.next.next.next.next.next =
new
ListNode(
0
);
int
K2 =
4
;
int
result2 = findKthLargestTribonacci(head2, K2);
System.out.println(
"The "
+ K2 +
"th largest Tribonacci number is: "
+ result2);
}
}