|
1 | 1 | # Insertion Sort List
|
2 | 2 |
|
| 3 | +Tags: Linked List, Sort, Medium |
| 4 | + |
3 | 5 | ## Question
|
4 | 6 |
|
5 |
| -- leetcode: [Insertion Sort List | LeetCode OJ](https://leetcode.com/problems/insertion-sort-list/) |
6 |
| -- lintcode: [(173) Insertion Sort List](http://www.lintcode.com/en/problem/insertion-sort-list/) |
| 7 | +- leetcode: [Insertion Sort List](https://leetcode.com/problems/insertion-sort-list/) |
| 8 | +- lintcode: [Insertion Sort List](https://www.lintcode.com/problem/insertion-sort-list/) |
| 9 | + |
| 10 | +### Problem Statement |
7 | 11 |
|
8 |
| -``` |
9 | 12 | Sort a linked list using insertion sort.
|
10 | 13 |
|
11 |
| -Example |
12 |
| -Given 1->3->2->0->null, return 0->1->2->3->null. |
13 |
| -``` |
| 14 | + |
| 16 | +A graphical example of insertion sort. The partial sorted list (black) |
| 17 | +initially contains only the first element in the list. |
| 18 | +With each iteration one element (red) is removed from the input data and |
| 19 | +inserted in-place into the sorted list |
| 20 | + |
| 21 | + |
| 22 | +**Algorithm of Insertion Sort:** |
| 23 | + |
| 24 | + 1. Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list. |
| 25 | + 2. 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. |
| 26 | + 3. It repeats until no input elements remain. |
| 27 | + |
| 28 | + |
| 29 | +**Example 1:** |
| 30 | + |
| 31 | + |
| 32 | + **Input:** 4->2->1->3 |
| 33 | + **Output:** 1->2->3->4 |
| 34 | + |
| 35 | + |
| 36 | +**Example 2:** |
| 37 | + |
| 38 | + |
| 39 | + **Input:** -1->5->3->4->0 |
| 40 | + **Output:** -1->0->3->4->5 |
| 41 | + |
14 | 42 |
|
15 | 43 | ## 题解1 - 从首到尾遍历
|
16 | 44 |
|
@@ -130,9 +158,9 @@ Python 的实现在 lintcode 上会提示 TLE, leetcode 上勉强通过,这里
|
130 | 158 |
|
131 | 159 | ### 复杂度分析
|
132 | 160 |
|
133 |
| -最好情况:原链表已经有序,每得到一个新节点都需要 $$i$$ 次比较和一次交换, 时间复杂度为 $$1/2O(n^2) + O(n)$$, 使用了 dummy 和 pre, 空间复杂度近似为 $$O(1)$$. |
| 161 | +最好情况:原链表已经逆序,每得到一个新节点仅需要一次比较, 时间复杂度为 $$O(n)$$, 使用了 dummy 和 pre, 空间复杂度近似为 $$O(1)$$. |
134 | 162 |
|
135 |
| -最坏情况:原链表正好逆序,由于是单向链表只能从前往后依次遍历,交换和比较次数均为 $$1/2 O(n^2)$$, 总的时间复杂度近似为 $$O(n^2)$$, 空间复杂度同上,近似为 $$O(1)$$. |
| 163 | +最坏情况:原链表正好升序,由于是单向链表只能从前往后依次遍历,交换和比较次数均为 $$1/2 O(n^2)$$, 总的时间复杂度近似为 $$O(n^2)$$, 空间复杂度同上,近似为 $$O(1)$$. |
136 | 164 |
|
137 | 165 | ## 题解2 - 优化有序链表
|
138 | 166 |
|
|
0 commit comments