Leetcode-147. Insertion Sort List
2016-10-31 20:14
411 查看
前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN,mcf171专栏。
博客链接:mcf171的博客
——————————————————————————————
Sort a linked list using insertion sort.
这个题目很困惑我,我的解法如下,会导致 Memory
Limit Exceeded
想通了,因为我没有调整指针的位置,导致链表有一个位置循环了。
博客链接: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; } }
想通了,因为我没有调整指针的位置,导致链表有一个位置循环了。
相关文章推荐
- LeetCode 147. Insertion Sort List
- leetcode147. Insertion Sort List
- [LeetCode]147. Insertion Sort List
- [LeetCode]147. Insertion Sort List
- Leetcode 147. Insertion Sort List
- leetcode之147. Insertion Sort List(C++解法)
- Leetcode 147. Insertion Sort List (Medium) (cpp)
- LeetCode 147. Insertion Sort List
- LeetCode 147. Insertion Sort List
- LeetCode 147. Insertion Sort List
- Leetcode 147. Insertion Sort List
- [LeetCode]147. Insertion Sort List 深入浅出讲解和代码示例
- [leetcode] 147. Insertion Sort List 解题报告
- 【Leetcode】147. Insertion Sort List
- leetcode 147. Insertion Sort List
- [LeetCode] 147. Insertion Sort List
- LeetCode 147. Insertion Sort List(插入有序链表)
- LeetCode 147. Insertion Sort List插入排序链表的高效简单解法
- [LeetCode] 147. Insertion Sort List
- 【LeetCode】147. Insertion Sort List