[LeetCode] Sort List
There are many merge-sort solutions at the forum, but very few quicksort solutions. So I post my accepted quicksort solution here.
Well, after reading the problem statement, I intuitively select quicksort since it is able to give an in-place solution and thus costs only constant space. Also, it is O(nlogn)
in the expected case though it may become O(n^2)
in the worst case.
Then I implement my quicksort solution and test it. I then submit it to the online judge. However, the annoying TLE error occurred. I check for the forums and some people suggested to use random pivoting or duplicate skipping. However, implementing random pivoting is a little costly, I lazily tried to skip the duplicates. And it works! So now comes the following solution . Note that each time I choose the first node as the pivot. Moreover, I create a new_head
that points to head
for convenience.
Of course, this solution passes the online judge luckily. If the linked list is like: 100000 -> 99999 -> 99998 -> ... -> 1
, it will fail since the subproblems only decrease by 1 at each recursion. However, it seems that the LeetCode OJ does not have this kind of test cases.
1 void sortListHelper(ListNode* head, ListNode* tail) { 2 if (head -> next == tail) return; 3 /* Partition the list. */ 4 ListNode* pre = head; 5 ListNode* cur = head -> next; 6 ListNode* pivot = cur; 7 while (cur -> next && cur -> next != tail) { 8 if (pivot -> val > cur -> next -> val) { 9 ListNode* temp = pre -> next; 10 pre -> next = cur -> next; 11 cur -> next = cur -> next -> next; 12 pre -> next -> next = temp; 13 } 14 else cur = cur -> next; 15 } 16 sortListHelper(head, pivot); 17 /* Here is the trick. */ 18 while (pivot -> next != tail && pivot -> next -> val == pivot -> val) 19 pivot = pivot -> next; 20 if (pivot -> next != tail) sortListHelper(pivot, tail); 21 } 22 23 ListNode* sortList(ListNode* head) { 24 ListNode* new_head = new ListNode(0); 25 new_head -> next = head; 26 sortListHelper(new_head, NULL); 27 return new_head -> next; 28 }
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
· ASP.NET Core 模型验证消息的本地化新姿势
· 从零开始开发一个 MCP Server!
· ThreeJs-16智慧城市项目(重磅以及未来发展ai)
· .NET 原生驾驭 AI 新基建实战系列(一):向量数据库的应用与畅想
· Ai满嘴顺口溜,想考研?浪费我几个小时
· Browser-use 详细介绍&使用文档