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

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

    Example 1:

    Input: 4->2->1->3
    Output: 1->2->3->4
    

    Example 2:

    Input: -1->5->3->4->0
    Output: -1->0->3->4->5

    divide and conquer + merge sort,先找中点,断开,再merge

    time: O(nlogn), space: O(1)

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        public ListNode sortList(ListNode head) {
            if(head == null || head.next == null) return head;
            ListNode mid = getMiddle(head);
            ListNode second = mid.next;
            mid.next = null;
            return merge(sortList(head), sortList(second));
        }
        
        private ListNode getMiddle(ListNode head) {
            ListNode fast = head;
            ListNode slow = head;
            while(fast.next != null && fast.next.next != null) {
                fast = fast.next.next;
                slow = slow.next;
            }
            return slow;
        }
        
        private ListNode merge(ListNode n1, ListNode n2) {
            ListNode dummy = new ListNode(-1);
            ListNode cur = dummy;
            while(n1 != null && n2 != null) {
                if(n1.val <= n2.val) {
                    cur.next = n1;
                    n1 = n1.next;
                }
                else {
                    cur.next = n2;
                    n2 = n2.next;
                }
                cur = cur.next;
            }
            if(n1 != null) cur.next = n1;
            if(n2 != null) cur.next = n2;
            
            return dummy.next;
        }
    }
  • 相关阅读:
    浅析WPhone、Android的Back与Home键
    Android音频播放之SoundPool
    Button、ImageButton及ImageView详解
    文本 To 音频
    gravity、layout_gravity及orientation
    项目规范性检测工具Lint
    Android视频播放之VideoView
    ContentProvider数据访问详解
    QQ第三方登录
    Android数据共享
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10145067.html
Copyright © 2011-2022 走看看