[LeetCode] Sort List

本文介绍了一种使用快速排序算法对链表进行排序的方法。通过选择首个节点作为基准,并采用跳过重复元素的策略,该解决方案成功避免了超时错误,并在预期情况下达到了O(nlogn)的时间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 headfor 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     }

 

转载于:https://www.cnblogs.com/jcliBlogger/p/4548064.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值