-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path148.cpp
More file actions
73 lines (71 loc) · 1.7 KB
/
Copy path148.cpp
File metadata and controls
73 lines (71 loc) · 1.7 KB
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
// mergeSort-52ms.cpp
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
ListNode *separate(ListNode *h) {
auto l = h, r = h;
ListNode *pre = nullptr;
while (r && r->next) {
r = r->next->next;
pre = l;
l = l->next;
}
if (pre)
pre->next = nullptr;
return l;
}
public:
ListNode *sortList(ListNode *head) {
if (!head || !head->next)
return head;
auto rp = separate(head);
rp = sortList(rp);
auto lp = sortList(head);
auto h = ListNode(0);
auto p = &h;
while (lp && rp) {
auto &smallP = (lp->val < rp->val) ? lp : rp;
p = p->next = smallP;
smallP = smallP->next;
}
for (auto cur = lp ? lp : rp; cur; cur = cur->next)
p = p->next = cur;
return h.next;
}
};
// quickSortO1Space-744ms.cpp
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution2 {
pair<ListNode *, ListNode *> helper(ListNode *head) {
if (!head)
return {nullptr, nullptr};
ListNode lh(0), rh(0);
ListNode *l = &lh, *r = &rh, *h = head;
for (auto p = head->next; p; p = p->next)
if (h->val < p->val)
r = r->next = p;
else
l = l->next = p;
r->next = l->next = nullptr;
auto lpart = helper(lh.next), rpart = helper(rh.next);
if (lh.next)
lpart.second->next = h;
h->next = rpart.first;
return {lh.next ? lpart.first : h, rh.next ? rpart.second : h};
}
public:
ListNode *sortList(ListNode *head) { return helper(head).first; }
};