您的位置:首页 > 其它

(Leetcode 147)Insertion Sort List

2016-03-17 21:26 381 查看
题目的原文是这样的:

Sort a linked list using insertion sort.

Subscribe to see which companies asked this question

解题思路:
1. 首先有一种最通俗一下就想到的解法,即是新建一个dummy头结点,然后每次将原head的结点取出来一个,再在dummy链表寻找合适的位置插入。这样解法的时间复杂度为O(n^2),比较耗时。

2. 还有一种解法,耗时比较少,这种方法没有建立虚头结点,插入的时候少了函数直接的跳转所耗费的时间,只是每次分情况讨论,分为三种情况讨论,插入点的值和头结点比较,和尾结点比较,和中间结点比较,时间效率在最坏的情况下也可以达到O(n^2),但是前期加入了预判断的话应该就可以省下很多时间。只是程序结构上面不如上面的解法一清晰一些。

下面先贴解题思路一的代码:

public class Solution {
public ListNode insertionSortList( ListNode head) {
if( head == null || head.next == null ){
return head;
}
ListNode dummy = new ListNode(Integer.MIN_VALUE);
dummy.next = null;
while( head != null ){
ListNode r = head.next;
ListNode insert = insertForPos( dummy,head.val );
head.next = insert.next;
insert.next = head;
head = r;
}

return dummy.next;
}
//该函数返回可以插入位置的前一个节点
public ListNode insertForPos( ListNode head, int val ){
ListNode pre= head, next= head.next;
while( next != null && next.val <= val ){
pre = next;
next = next.next;
}
return pre;
}
}
思路一耗时较长,为38ms。

下面贴解题思路二的代码:

public class Solution {
public ListNode insertionSortList(ListNode head) {
if (head == null || head.next == null){
return head;
}

ListNode sortedHead = head, sortedTail = head;
head = head.next;
sortedHead.next = null;

while (head != null){
//取出将要比较的节点,并且将其设置为孤立的节点
ListNode temp = head;
head = head.next;
temp.next = null;

//如果该节点的值小于sortedHead,则将其插入头部前
if (temp.val <= sortedHead.val){
temp.next = sortedHead;
sortedTail = ( sortedHead.next == null ? sortedHead : sortedTail );
sortedHead = temp;
}
//如果该节点的值大于tail尾节点,则将其插在最后
else if (temp.val >= sortedTail.val){
sortedTail.next = temp;
sortedTail = sortedTail.next;
}
//如果新的节点介于中间,则遍历为其找到一个合适的位置插入
else{
ListNode current = sortedHead;
while (current.next != null && current.next.val < temp.val) {
current = current.next;
}

temp.next = current.next;
current.next = temp;
}
}

return sortedHead;
}
}


这种解法耗时8ms。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: