Skip to content

Commit bf90045

Browse files
refactor 147
1 parent 357ef82 commit bf90045

File tree

1 file changed

+42
-22
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+42
-22
lines changed

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

+42-22
Original file line numberDiff line numberDiff line change
@@ -6,33 +6,53 @@
66
import java.util.List;
77

88
/**
9+
* 147. Insertion Sort List
10+
*
911
* 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
1029
*/
1130
public class _147 {
1231

32+
public static class Solution1 {
1333
public ListNode insertionSortList(ListNode head) {
14-
ListNode temp = head;
15-
List<Integer> list = new ArrayList<Integer>();
16-
while (temp != null) {
17-
list.add(temp.val);
18-
temp = temp.next;
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+
}
1948
}
20-
Integer[] nums = list.toArray(new Integer[list.size()]);
21-
for (int i = 1; i < list.size(); i++) {
22-
for (int j = i - 1; j >= 0; j--) {
23-
if (nums[j] > nums[j + 1]) {
24-
int tempNum = nums[j];
25-
nums[j] = nums[j + 1];
26-
nums[j + 1] = tempNum;
27-
}
28-
}
29-
}
30-
ListNode newHead = head;
31-
for (int i = 0; i < nums.length; i++) {
32-
newHead.val = nums[i];
33-
newHead = newHead.next;
34-
}
35-
return head;
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;
3656
}
37-
57+
}
3858
}

0 commit comments

Comments
 (0)