LeetCode 148. Sort List–面试算法题–C++,Python解法
LeetCode题解专栏:LeetCode题解
LeetCode 所有题目总结:LeetCode 所有题目总结
大部分题目C++,Python,Java的解法都有。
题目地址:Sort List - LeetCode
Sort a linked list in O(n log n) time using constant space complexity.
Example 1:
Input: 4->2->1->3
Output: 1->2->3->4
Example 2:
Input: -1->5->3->4->0
Output: -1->0->3->4->5
我在现场面的时候,做的算法题是对单向链表进行选择排序。
如果使用Std中的排序,做法如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
bool judge(ListNode *left, ListNode *r) {
return left->val < r->val;
}
class Solution {
public:
ListNode *sortList(ListNode *head) {
if (head == NULL) {
return NULL;
}
vector<ListNode *> l;
while (head != nullptr) {
l.push_back(head);
head = head->next;
}
std::sort(l.begin(), l.end(), judge);
for (int i = 0; i < l.size() - 1; i++) {
l[i]->next = l[i + 1];
}
l[l.size() - 1]->next = NULL;
return l[0];
}
};
这个解法不是最优的,因为要把所有节点都加入vector中。
但速度已经比较快了。
如果想要空间复杂度降到 O(1),需要用归并排序,迭代的做法,写起来真的难。我就不写了。