您的位置:首页 > 编程语言 > C语言/C++

148[Medium]: Sort List

2017-11-03 23:12 381 查看
Part1:问题描述

Sort a linked list in O(n log n)
time using constant space complexity.

Part2:解题思路

我看到他说时间复杂度为O(nlogn)就想到所有的排序里只有快排能达到这个标准,然后进一步想到#include<algorithm>里有直接的排序函数可以调用。用连续空间就想到了数组,但是由于不知道有多少元素,就用变长数组vector。所以我就是先把链表里的元素拿到vector里排个序,再将排完的数据插回到链表中。

感觉,这道题可能希望我们自己实现一个快排吧,由于我想睡觉就先这样吧,之后再继续补充。

其实对链表排序,直接改指针也是很好的,各种复杂度都很低,以后再更吧。先匿了


Part3:代码

ListNode* sortList(ListNode* head) {
vector<int> num;
if (head == NULL) return head;
ListNode* current;
current = head;
while (current != NULL) {
num.push_back(current->val);
current = current->next;
}
sort(num.begin(), num.end());
current = head;
int index = 0;
while(current != NULL) {
current->val = num[index++];
current = current->next;
}
return head;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++ linkedlist