-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReorderList.java
More file actions
61 lines (52 loc) · 1.15 KB
/
ReorderList.java
File metadata and controls
61 lines (52 loc) · 1.15 KB
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
54
55
56
57
58
59
60
61
package linkedlist;
import java.util.*;
import linkedlist.LinkedListTest.ListNode;
/**
* @author Shogo Akiyama
* Solved on 08/22/2019
*
* 143. Reorder List
* https://leetcode.com/problems/reorder-list/
* Difficulty: Medium
*
* Approach: Recursion & HashTable
* Runtime: 8 ms, faster than 9.28% of Java online submissions for Reorder List.
* Memory Usage: 46.1 MB, less than 6.82% of Java online submissions for Reorder List.
*
* @see LinkedListTest#testReorderList()
*/
public class ReorderList {
Map<Integer, ListNode> map = new HashMap<Integer, ListNode>();
int size;
int left;
int right;
public void reorderList(ListNode head) {
if (head == null) {
return;
}
add(head, 0);
size = map.size();
left = size - 1;
right = 0;
head.next = reorder(left);
}
private void add(ListNode node, int index) {
if (node == null) {
return;
}
map.put(index, node);
add(node.next, ++index);
}
private ListNode reorder(int index) {
if (left <= right) {
return null;
}
ListNode node = map.get(index);
if (index >= size / 2) {
node.next = reorder(++right);
} else {
node.next = reorder(--left);
}
return node;
}
}