Leetcode 148. Sort List

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Sort List

2. Solution

  • Version 1
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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* sortList(ListNode* head) {
if(!head) {
return NULL;
}
vector<ListNode*> nodes;
ListNode* current = head;
while(current) {
int index = binarySearch(nodes, current->val);
nodes.insert(nodes.begin() + index, current);
current = current->next;
}
ListNode* result = nodes[0];
current = nodes[0];
for(int i = 1; i < nodes.size(); i++) {
current->next = nodes[i];
current = current->next;
}
current->next = NULL;
return result;
}

private:
int binarySearch(vector<ListNode*>& nodes, int target) {
int left = 0;
int right = nodes.size() - 1;
while(left <= right) {
int mid = (left + right) / 2;
if(nodes[mid]->val > target) {
right = mid - 1;
}
else if(nodes[mid]->val < target) {
left = mid + 1;
}
else {
return mid;
}
}
return left;
}
};
  • Version 2
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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* sortList(ListNode* head) {
if(!head || !head->next) {
return head;
}
ListNode* pre = nullptr;
ListNode* slow = head;
ListNode* fast = head;
while (fast != nullptr && fast->next != nullptr) {
pre = slow;
slow = slow->next;
fast = fast->next->next;
}
pre->next = nullptr;
ListNode* l1 = sortList(head);
ListNode* l2 = sortList(slow);
return mergeTwoLists(l1, l2);
}

private:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode* ptrFirst = l1;
ListNode* ptrSecond = l2;
ListNode* head = new ListNode(0);
ListNode* current = head;
while(ptrFirst && ptrSecond) {
if(ptrFirst->val > ptrSecond->val) {
current->next = ptrSecond;
ptrSecond = ptrSecond->next;
}
else {
current->next = ptrFirst;
ptrFirst = ptrFirst->next;
}
current = current->next;
}
if(ptrFirst) {
current->next = ptrFirst;
}
if(ptrSecond) {
current->next = ptrSecond;
}
return head->next;
}
};

Reference

  1. https://leetcode.com/problems/sort-list/description/
如果有收获,可以请我喝杯咖啡!