zoukankan      html  css  js  c++  java
  • Leetcode 148. Sort List

    Sort a linked list in O(n log n) time using constant space complexity.


    Analysis:

    1. use merge sort

    2. use quick sort


    Java code

    20160601 

    merge sort:

    /**
     * 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) {
            //use merge sort
            //base case
            if (head == null || head.next == null) {
                return head;
            }
            ListNode mid = findMiddle(head);
            ListNode right = sortList(mid.next);
            mid.next = null;
            ListNode left = sortList(head);
            return merge(left, right);
        }
        
        private ListNode findMiddle(ListNode head) {
            //base case
            if (head == null || head.next == null) {
                return head;
            }
            ListNode slow = head, fast = head;
            while (fast.next != null && fast.next.next != null) {
                slow = slow.next;
                fast = fast.next.next;
            }
            return slow;
        }
        
        private ListNode merge(ListNode left, ListNode right) {
            ListNode dummy = new ListNode(0);
            ListNode cur = dummy;
            while (left != null && right != null) {
                if (left.val <= right.val) {
                    cur.next = left;
                    left = left.next;
                } else {
                    cur.next = right;
                    right = right.next;
                }
                cur = cur.next;
            }
            if (left != null) {
                cur.next = left;
            }
            if (right != null) {
                cur.next = right;
            }
            return dummy.next;
        }
    }
  • 相关阅读:
    标识符和关键字
    大任务拆成小任务,再到可并行的小任务
    莫等闲
    这样修改有哪些优缺点 wcf service via attribute setting vs config
    头脑发达,四肢简单
    32位还是64位
    session未释放
    split task
    sqlserver deadlock
    IronPython
  • 原文地址:https://www.cnblogs.com/anne-vista/p/5551855.html
Copyright © 2011-2022 走看看