zoukankan      html  css  js  c++  java
  • LeetCode 147. Insertion Sort List (对链表进行插入排序)

    题目标签:Sort

      遍历Linked List,把每一个点, 放到新的list里 合适的位置。具体看code。

    Java Solution: 

    Runtime:  30 ms, faster than 41.35% 

    Memory Usage: 39MB, less than 72.23%

    完成日期:6/13/2020

    关键点:Linked List, Insertion Sort

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode() {}
     *     ListNode(int val) { this.val = val; }
     *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
     * }
     */
    class Solution {
        public ListNode insertionSortList(ListNode head) {
            if(head == null) {
                return head;
            }
            
            ListNode helper = new ListNode(0); // new starter of the sorted list
            ListNode cur = head; // this node will be inserted
            ListNode pre = helper; // insert node between pre and pre.next
            ListNode next = null; // the next node will be inserted
            
            // go through list
            while(cur != null) {
                next = cur.next;
                
                // find the right place to insert next node
                while(pre.next != null && pre.next.val < cur.val) {
                    pre = pre.next;
                }
                
                // insert between pre and pre.next
                cur.next = pre.next;
                pre.next = cur;
                pre = helper;
                cur = next;
            }
            
            return helper.next;
        }
    }

    参考资料:https://leetcode.com/problems/insertion-sort-list/discuss/46420/An-easy-and-clear-way-to-sort-(-O(1)-space-)

    LeetCode 题目列表 - LeetCode Questions List

    题目来源:https://leetcode.com/

  • 相关阅读:
    MyBatis+Oracle+Sequence
    原来这就是JVM垃圾
    JVM内存布局
    CacheAsidePattern结论
    The LMAX Architecture
    网络编程
    随机存取文件流
    数据流
    打印流
    标准输入流、标准输出流
  • 原文地址:https://www.cnblogs.com/jimmycheng/p/13122787.html
Copyright © 2011-2022 走看看