- Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy path_1721.java
108 lines (100 loc) · 3.23 KB
/
_1721.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
packagecom.fishercoder.solutions.secondthousand;
importcom.fishercoder.common.classes.ListNode;
importjava.util.ArrayList;
importjava.util.List;
publicclass_1721 {
publicstaticclassSolution1 {
publicListNodeswapNodes(ListNodehead, intk) {
List<Integer> list = newArrayList<>();
ListNodetmp = head;
while (tmp != null) {
list.add(tmp.val);
tmp = tmp.next;
}
intfirst = list.get(k - 1);
intsize = list.size();
intsecond = list.get(size - k);
list.remove(k - 1);
list.add(k - 1, second);
list.remove(size - k);
list.add(size - k, first);
ListNodepre = newListNode(-1);
tmp = pre;
for (inti = 0; i < list.size(); i++) {
pre.next = newListNode(list.get(i));
pre = pre.next;
}
returntmp.next;
}
}
publicstaticclassSolution2 {
publicListNodeswapNodes(ListNodehead, intk) {
if (head == null || head.next == null) {
returnhead;
}
// find length of list
intn = 0;
ListNodecurrent = head;
while (current != null) {
current = current.next;
n++;
}
int[] nums = newint[n];
current = head;
inti = 0;
while (current != null) {
nums[i++] = current.val;
current = current.next;
}
intfirstIndex;
intsecondIndex;
firstIndex = k;
secondIndex = n - k;
inttemp = nums[firstIndex - 1];
nums[firstIndex - 1] = nums[secondIndex];
nums[secondIndex] = temp;
ListNodedummy = newListNode(-1);
current = dummy;
for (i = 0; i < n; i++) {
ListNodenode = newListNode(nums[i]);
current.next = node;
current = current.next;
}
returndummy.next;
}
}
publicstaticclassSolution3 {
publicListNodeswapNodes(ListNodehead, intk) {
// O(n) linear time
/*
1. Calculate length of linked list
2. Initialize 3 ptrs, temp1 and temp2 used for pointing to nodes at k, (len - k + 1)
and temp3 used to iterate over the linked list
*/
intlength = 0;
intsecondIndex;
ListNodetemp1 = null;
ListNodetemp2 = null;
ListNodetemp3 = head;
while (temp3 != null) {
length++;
temp3 = temp3.next;
}
secondIndex = length - k + 1;
temp3 = head;
for (inti = 1; i <= length; i++) {
if (i == k) {
temp1 = temp3;
}
if (i == secondIndex) {
temp2 = temp3;
}
temp3 = temp3.next;
}
intvalue = temp1.val;
temp1.val = temp2.val;
temp2.val = value;
returnhead;
}
}
}