leetcode 148. Sort List ----- java
2024-10-19 21:23:50
Sort a linked list in O(n log n) time using constant space complexity.
排序,要求是O(nlog(n))的时间复杂度和常数的空间复杂度,那么就使用归并就可以了。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution { public ListNode sortList(ListNode head) {
if( head == null || head.next == null)
return head; int size = 1;
ListNode start = new ListNode(0);
start.next = head; while( true ){
ListNode node1 = start;
ListNode node2 = start.next;
for( int i = 0 ; i < size && node2!=null;i++){
node2 = node2.next;
} if( node2 == null )
break;
ListNode nnn = start.next; while( node2 != null ){
node1 = helper(node1,node2,size);
if( node1 == null )
break;
node2 = node1.next;
for( int i = 0 ; i< size && node2 != null;i++){
node2 = node2.next;
}
}
size*=2;
}
return start.next;
} public ListNode helper(ListNode node1,ListNode node2,int size){ int num1 = 0,num2 = 0; ListNode node = null; if( node1.next.val < node2.val ){
node = node1.next;
node1 = node1.next.next;
num1++;
}else{
ListNode nn = node1.next;
node1.next = node2;
node1 = nn;
node = node2;
node2 = node2.next;
num2++;
} while( num1 < size && num2 < size && node1 != null && node2 != null){ if( node1.val < node2.val ){
node.next = node1;
node = node1;
node1 = node1.next;
num1++;
}else{
node.next = node2;
node = node2;
node2 = node2.next;
num2++;
}
}
while( num1 < size && node1 != null){
node.next = node1;
node = node1;
node1 = node1.next;
num1++;
} while( num2 < size && node2 != null){
node.next = node2;
node = node2;
node2 = node2.next;
num2++;
}
node.next = node2;
return node; }
}
最新文章
- Worktile协同特色之一:无处不在的关注
- xamarin 手机顶部状态栏
- 虚拟机利用Host-only实现在不插网线的情况下,虚拟机与主机实现双向通信,实现ssh连接以及samba服务实现共享
- 使用TCMalloc的堆栈检查
- Iterator<;转>;
- 算法:C++排列组合
- jquery的小插件(按钮抖动)——衍生QQ窗口抖动
- memcached原理全面剖析
- 我不知道你是在一个多线程out该--【ITOO】
- 字符函数库 - cctype 和 climits 中的符号常量
- C++第二天
- 《JS权威指南学习总结--第十一章子集和扩展》
- centos6.8 docker0: iptables: No chain/target/match by that name
- 向量 dot cross product 点积叉积 几何意义
- AJAX工作原理与缺点
- Spring Boot Log4j2 日志学习
- python string.py 源码分析 二:capwords
- day 06云计算的三种服务模式:IaaS,PaaS和SaaS
- 嵌入式linux查看磁盘占用情况df -h
- SQL记录-PLSQL日期与时间