|
6 | 6 | import java.util.List;
|
7 | 7 |
|
8 | 8 | /**
|
| 9 | + * 147. Insertion Sort List |
| 10 | + * |
9 | 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 |
10 | 29 | */
|
11 | 30 | public class _147 {
|
12 | 31 |
|
| 32 | + public static class Solution1 { |
13 | 33 | 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 | + } |
19 | 48 | }
|
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; |
36 | 56 | }
|
37 |
| - |
| 57 | + } |
38 | 58 | }
|
0 commit comments