forked from soulmachine/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchapSorting.tex
423 lines (323 loc) · 10.9 KB
/
chapSorting.tex
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
\chapter{排序}
\section{Merge Sorted Array} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:merge-sorted-array}
\subsubsection{描述}
Given two sorted integer arrays A and B, merge B into A as one sorted array.
Note:
You may assume that A has enough space to hold additional elements from B. The number of elements initialized in A and B are m and n respectively.
\subsubsection{分析}
无
\subsubsection{代码}
\begin{Code}
//LeetCode, Merge Sorted Array
// 时间复杂度O(m+n),空间复杂度O(1)
class Solution {
public:
void merge(int A[], int m, int B[], int n) {
int ia = m - 1, ib = n - 1, icur = m + n - 1;
while(ia >= 0 && ib >= 0) {
A[icur--] = A[ia] >= B[ib] ? A[ia--] : B[ib--];
}
while(ib >= 0) {
A[icur--] = B[ib--];
}
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Merge Two Sorted Lists,见 \S \ref{sec:merge-two-sorted-lists}
\item Merge k Sorted Lists,见 \S \ref{sec:merge-k-sorted-lists}
\myenddot
\section{Merge Two Sorted Lists} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:merge-two-sorted-lists}
\subsubsection{描述}
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
\subsubsection{分析}
无
\subsubsection{代码}
\begin{Code}
//LeetCode, Merge Two Sorted Lists
// 时间复杂度O(min(m,n)),空间复杂度O(1)
class Solution {
public:
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
if (l1 == nullptr) return l2;
if (l2 == nullptr) return l1;
ListNode dummy(-1);
ListNode *p = &dummy;
for (; l1 != nullptr && l2 != nullptr; p = p->next) {
if (l1->val > l2->val) { p->next = l2; l2 = l2->next; }
else { p->next = l1; l1 = l1->next; }
}
p->next = l1 != nullptr ? l1 : l2;
return dummy.next;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Merge Sorted Array \S \ref{sec:merge-sorted-array}
\item Merge k Sorted Lists,见 \S \ref{sec:merge-k-sorted-lists}
\myenddot
\section{Merge k Sorted Lists} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:merge-k-sorted-lists}
\subsubsection{描述}
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
\subsubsection{分析}
可以复用Merge Two Sorted Lists(见 \S \ref{sec:merge-two-sorted-lists})的函数
\subsubsection{代码}
\begin{Code}
//LeetCode, Merge k Sorted Lists
// 时间复杂度O(n1+n2+...),空间复杂度O(1)
class Solution {
public:
ListNode *mergeKLists(vector<ListNode *> &lists) {
if (lists.size() == 0) return nullptr;
ListNode *p = lists[0];
for (int i = 1; i < lists.size(); i++) {
p = mergeTwoLists(p, lists[i]);
}
return p;
}
// Merge Two Sorted Lists
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
ListNode head(-1);
for (ListNode* p = &head; l1 != nullptr || l2 != nullptr; p = p->next) {
int val1 = l1 == nullptr ? INT_MAX : l1->val;
int val2 = l2 == nullptr ? INT_MAX : l2->val;
if (val1 <= val2) {
p->next = l1;
l1 = l1->next;
} else {
p->next = l2;
l2 = l2->next;
}
}
return head.next;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Merge Sorted Array \S \ref{sec:merge-sorted-array}
\item Merge Two Sorted Lists,见 \S \ref{sec:merge-two-sorted-lists}
\myenddot
\section{Insertion Sort List} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:Insertion-Sort-List}
\subsubsection{描述}
Sort a linked list using insertion sort.
\subsubsection{分析}
无
\subsubsection{代码}
\begin{Code}
// LeetCode, Insertion Sort List
// 时间复杂度O(n^2),空间复杂度O(1)
class Solution {
public:
ListNode *insertionSortList(ListNode *head) {
ListNode dummy(INT_MIN);
//dummy.next = head;
for (ListNode *cur = head; cur != nullptr;) {
auto pos = findInsertPos(&dummy, cur->val);
ListNode *tmp = cur->next;
cur->next = pos->next;
pos->next = cur;
cur = tmp;
}
return dummy.next;
}
ListNode* findInsertPos(ListNode *head, int x) {
ListNode *pre = nullptr;
for (ListNode *cur = head; cur != nullptr && cur->val <= x;
pre = cur, cur = cur->next)
;
return pre;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Sort List, 见 \S \ref{sec:Sort-List}
\myenddot
\section{Sort List} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:Sort-List}
\subsubsection{描述}
Sort a linked list in $O(n log n)$ time using constant space complexity.
\subsubsection{分析}
常数空间且$O(nlogn)$,单链表适合用归并排序,双向链表适合用快速排序。本题可以复用 "Merge Two Sorted Lists" 的代码。
\subsubsection{代码}
\begin{Code}
// LeetCode, Sort List
// 归并排序,时间复杂度O(nlogn),空间复杂度O(1)
class Solution {
public:
ListNode *sortList(ListNode *head) {
if (head == NULL || head->next == NULL)return head;
// 快慢指针找到中间节点
ListNode *fast = head, *slow = head;
while (fast->next != NULL && fast->next->next != NULL) {
fast = fast->next->next;
slow = slow->next;
}
// 断开
fast = slow;
slow = slow->next;
fast->next = NULL;
ListNode *l1 = sortList(head); // 前半段排序
ListNode *l2 = sortList(slow); // 后半段排序
return mergeTwoLists(l1, l2);
}
// Merge Two Sorted Lists
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
ListNode dummy(-1);
for (ListNode* p = &dummy; l1 != nullptr || l2 != nullptr; p = p->next) {
int val1 = l1 == nullptr ? INT_MAX : l1->val;
int val2 = l2 == nullptr ? INT_MAX : l2->val;
if (val1 <= val2) {
p->next = l1;
l1 = l1->next;
} else {
p->next = l2;
l2 = l2->next;
}
}
return dummy.next;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Insertion Sort List,见 \S \ref{sec:Insertion-Sort-List}
\myenddot
\section{First Missing Positive} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:first-missing-positive}
\subsubsection{描述}
Given an unsorted integer array, find the first missing positive integer.
For example,
Given \fn{[1,2,0]} return \fn{3},
and \fn{[3,4,-1,1]} return \fn{2}.
Your algorithm should run in $O(n)$ time and uses constant space.
\subsubsection{分析}
本质上是桶排序(bucket sort),每当\fn{A[i]!= i+1}的时候,将A[i]与A[A[i]-1]交换,直到无法交换为止,终止条件是 \fn{A[i]== A[A[i]-1]}。
\subsubsection{代码}
\begin{Code}
// LeetCode, First Missing Positive
// 时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
int firstMissingPositive(int A[], int n) {
bucket_sort(A, n);
for (int i = 0; i < n; ++i)
if (A[i] != (i + 1))
return i + 1;
return n + 1;
}
private:
static void bucket_sort(int A[], int n) {
for (int i = 0; i < n; i++) {
while (A[i] != i + 1) {
if (A[i] <= 0 || A[i] > n || A[i] == A[A[i] - 1])
break;
swap(A[i], A[A[i] - 1]);
}
}
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Sort Colors, 见 \S \ref{sec:sort-colors}
\myenddot
\section{Sort Colors} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:sort-colors}
\subsubsection{描述}
Given an array with $n$ objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
Note:
You are not suppose to use the library's sort function for this problem.
\textbf{Follow up:}
A rather straight forward solution is a two-pass algorithm using counting sort.
First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's.
Could you come up with an one-pass algorithm using only constant space?
\subsubsection{分析}
由于0, 1, 2 非常紧凑,首先想到计数排序(counting sort),但需要扫描两遍,不符合题目要求。
由于只有三种颜色,可以设置两个index,一个是red的index,一个是blue的index,两边往中间走。时间复杂度$O(n)$,空间复杂度$O(1)$。
第3种思路,利用快速排序里 partition 的思想,第一次将数组按0分割,第二次按1分割,排序完毕,可以推广到$n$种颜色,每种颜色有重复元素的情况。
\subsubsection{代码1}
\begin{Code}
// LeetCode, Sort Colors
// Counting Sort
// 时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
void sortColors(int A[], int n) {
int counts[3] = { 0 }; // 记录每个颜色出现的次数
for (int i = 0; i < n; i++)
counts[A[i]]++;
for (int i = 0, index = 0; i < 3; i++)
for (int j = 0; j < counts[i]; j++)
A[index++] = i;
}
};
\end{Code}
\subsubsection{代码2}
\begin{Code}
// LeetCode, Sort Colors
// 双指针,时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
void sortColors(int A[], int n) {
// 一个是red的index,一个是blue的index,两边往中间走
int red = 0, blue = n - 1;
for (int i = 0; i < blue + 1;) {
if (A[i] == 0)
swap(A[i++], A[red++]);
else if (A[i] == 2)
swap(A[i], A[blue--]);
else
i++;
}
}
};
\end{Code}
\subsubsection{代码3}
\begin{Code}
// LeetCode, Sort Colors
// use partition()
// 时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
void sortColors(int A[], int n) {
partition(partition(A, A + n, bind1st(equal_to<int>(), 0)), A + n,
bind1st(equal_to<int>(), 1));
}
};
\end{Code}
\subsubsection{代码4}
\begin{Code}
// LeetCode, Sort Colors
// 重新实现 partition()
// 时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
void sortColors(int A[], int n) {
partition(partition(A, A + n, bind1st(equal_to<int>(), 0)), A + n,
bind1st(equal_to<int>(), 1));
}
private:
template<typename ForwardIterator, typename UnaryPredicate>
ForwardIterator partition(ForwardIterator first, ForwardIterator last,
UnaryPredicate pred) {
auto pos = first;
for (; first != last; ++first)
if (pred(*first))
swap(*first, *pos++);
return pos;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item First Missing Positive, 见 \S \ref{sec:first-missing-positive}
\myenddot