-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy path_2487.java
53 lines (48 loc) · 1.69 KB
/
_2487.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package com.fishercoder.solutions.thirdthousand;
import com.fishercoder.common.classes.ListNode;
import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
public class _2487 {
public static class Solution1 {
/*
* This is sort of cheating, i.e. transforming the linked list into an array instead of operating on the linked list itself.
*/
public ListNode removeNodes(ListNode head) {
List<Integer> list = getList(head);
Deque<Integer> rightBiggest = getRightBiggest(list);
ListNode pre = new ListNode(-1);
ListNode tmp = pre;
for (int i = 0; i < list.size(); i++) {
if (list.get(i) >= rightBiggest.pollFirst()) {
tmp.next = new ListNode(list.get(i));
tmp = tmp.next;
}
}
return pre.next;
}
private Deque<Integer> getRightBiggest(List<Integer> list) {
Deque<Integer> result = new LinkedList<>();
int max = list.get(list.size() - 1);
result.addFirst(max);
for (int i = list.size() - 2; i >= 0; i--) {
max = Math.max(max, list.get(i));
result.addFirst(max);
}
return result;
}
private List<Integer> getList(ListNode head) {
ListNode tmp = head;
List<Integer> list = new ArrayList<>();
while (tmp != null) {
list.add(tmp.val);
tmp = tmp.next;
}
return list;
}
}
public static class Solution2 {
// TODO: use stack to solve this problem
}
}