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;
}
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;
}
相关文章推荐
- [Leetcode 148, medium] Sort List
- Leetcode 148 Sort List
- LeetCode 148. Sort List
- leetcode 148 sort List
- LeetCode-148. Sort List
- Leetcode: 148. Sort List
- Sort List 148
- leetcode/algorithm 148. Sort List
- 148. Sort List
- [leetcode 148] Sort List
- Leetcode# 148 Sort List
- 148. Sort List
- [LeetCode]148 Sort List
- [leedcode 148] Sort List
- LeetCode148 Sort List
- [LeetCode]148. Sort List
- LeetCode 148. Sort List
- LeetCode148 Sort List
- [LeetCode 148] Sort List
- leetcode 148. Sort List