Skip to content

Commit 228193f

Browse files
refactor 147
1 parent 31e48b6 commit 228193f

File tree

1 file changed

+24
-46
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+24
-46
lines changed

src/main/java/com/fishercoder/solutions/_147.java

Lines changed: 24 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -5,54 +5,32 @@
55
import java.util.ArrayList;
66
import java.util.List;
77

8-
/**
9-
* 147. Insertion Sort List
10-
*
11-
* Sort a linked list using insertion sort.
12-
*
13-
* Algorithm of Insertion Sort:
14-
*
15-
* Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list.
16-
* At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there.
17-
* It repeats until no input elements remain.
18-
*
19-
*
20-
* Example 1:
21-
*
22-
* Input: 4->2->1->3
23-
* Output: 1->2->3->4
24-
*
25-
* Example 2:
26-
*
27-
* Input: -1->5->3->4->0
28-
* Output: -1->0->3->4->5
29-
*/
308
public class _147 {
319

32-
public static class Solution1 {
33-
public ListNode insertionSortList(ListNode head) {
34-
ListNode temp = head;
35-
List<Integer> list = new ArrayList<>();
36-
while (temp != null) {
37-
list.add(temp.val);
38-
temp = temp.next;
39-
}
40-
Integer[] nums = list.toArray(new Integer[list.size()]);
41-
for (int i = 1; i < list.size(); i++) {
42-
for (int j = i - 1; j >= 0; j--) {
43-
if (nums[j] > nums[j + 1]) {
44-
int tempNum = nums[j];
45-
nums[j] = nums[j + 1];
46-
nums[j + 1] = tempNum;
47-
}
10+
public static class Solution1 {
11+
public ListNode insertionSortList(ListNode head) {
12+
ListNode temp = head;
13+
List<Integer> list = new ArrayList<>();
14+
while (temp != null) {
15+
list.add(temp.val);
16+
temp = temp.next;
17+
}
18+
Integer[] nums = list.toArray(new Integer[list.size()]);
19+
for (int i = 1; i < list.size(); i++) {
20+
for (int j = i - 1; j >= 0; j--) {
21+
if (nums[j] > nums[j + 1]) {
22+
int tempNum = nums[j];
23+
nums[j] = nums[j + 1];
24+
nums[j + 1] = tempNum;
25+
}
26+
}
27+
}
28+
ListNode newHead = head;
29+
for (int i = 0; i < nums.length; i++) {
30+
newHead.val = nums[i];
31+
newHead = newHead.next;
32+
}
33+
return head;
4834
}
49-
}
50-
ListNode newHead = head;
51-
for (int i = 0; i < nums.length; i++) {
52-
newHead.val = nums[i];
53-
newHead = newHead.next;
54-
}
55-
return head;
5635
}
57-
}
5836
}

0 commit comments

Comments
 (0)