您的位置:首页 > 编程语言 > Java开发

Leetcode-147. Insertion Sort List

2016-10-31 20:14 411 查看
前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN,mcf171专栏。

博客链接:mcf171的博客

——————————————————————————————
Sort a linked list using insertion sort.
这个题目很困惑我,我的解法如下,会导致 Memory
Limit Exceeded

public class Solution {
    public ListNode insertionSortList(ListNode head) {
        if(head == null) return head;
        ListNode headNode = new ListNode(0);
        headNode.next = head;
        ListNode cur = head, iterNode = head.next;
        while(iterNode != null){
            cur = iterNode; iterNode = iterNode.next;
            ListNode pre = headNode;
            while(pre.next != iterNode)
            {
                if(cur.val < pre.next.val){
                    cur.next= pre.next;
                    pre.next = cur;
                    break;
                }else{
                    pre = pre.next;
                }

            }
        }
        return headNode.next;
    }
}
按照一个过了改了下,发现没有什么不同啊,有点想不通。Your runtime beats 29.75% of java submissions.

public class Solution {
public ListNode insertionSortList(ListNode head) {
if(head == null) return head;

ListNode helper = new ListNode(0);

ListNode cur = head, next,pre = helper;
while(cur != null){
next = cur.next;
while(pre.next != null && pre.next.val < cur.val)pre = pre.next;
cur.next = pre.next;
pre.next= cur;
pre = helper;
cur = next;
}
return helper.next;
}
}

想通了,因为我没有调整指针的位置,导致链表有一个位置循环了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java leetcode 算法