博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Sort List
阅读量:7104 次
发布时间:2019-06-28

本文共 2251 字,大约阅读时间需要 7 分钟。

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     }

 

转载地址:http://epjhl.baihongyu.com/

你可能感兴趣的文章
详解Java中ArrayList、Vector、LinkedList三者的异同点(转)
查看>>
Cookie基础
查看>>
禁用apache模块
查看>>
[zz]堆栈溢出的运行时探测
查看>>
java 动态代理学习(Proxy,InvocationHandler)
查看>>
MySQL——数据类型
查看>>
Python--操作excel
查看>>
认识全面的null
查看>>
Mysql查询缓存Query_cache的功用
查看>>
Domains域
查看>>
zabbix系列~mysql进行监控
查看>>
Eclipse格式化代码,自动换行设置
查看>>
RabbitMQ消息队列
查看>>
进程的方法和属性介绍
查看>>
内容页分页代码
查看>>
MS SQL Server迁移至Azure SQL(官方工具)
查看>>
jquery.cookie.js 删除cookie
查看>>
两点到圆的最小距离
查看>>
实数的构造(后记)
查看>>
vue中改elementUI默认样式引发的static 与 assets的区别
查看>>