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

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

    思路:要想时间复杂度达到O(n log n) ,那么有两种。一种是合并排序,还有一种是高速排序,而要想空间复杂度为常数。那么仅仅能使用递归,本人使用的是递归的合并排序。代码例如以下:
    /**
     * Definition for singly-linked list.
     * class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) {
     *         val = x;
     *         next = null;
     *     }
     * }
     */
    public class Solution {
       private ListNode merge(ListNode l1, ListNode l2) {
            if(l1==null&&l2==null) return null;
            ListNode head=new ListNode (-1);
            ListNode pNode=head;
            while(l1!=null||l2!=null){
    			if(l1==null) {
    				pNode.next=l2;
    				return head.next;
    			}
    			if(l2==null){
    				pNode.next=l1;
    				return head.next;
    			}
                if(l1.val>l2.val){
    				pNode.next=l2;
    				l2=l2.next;
                }else {
    				pNode.next=l1;
    				l1=l1.next;
                }
                pNode=pNode.next;                   
            }
            return head.next;
        }
       private ListNode mergeSort(ListNode head){
           if(head==null||head.next==null)   //just one element
               return head;
           ListNode p=head, q=head, pre=null;
           while(q!=null&&q.next!=null){
               q=q.next.next;
               pre=p;
               p=p.next;  //divide into two parts
           }
           pre.next=null;
           ListNode lhalf=mergeSort(head);
           ListNode rhalf=mergeSort(p);  //recursive
           return merge(lhalf, rhalf);   //merge
       }
        public ListNode sortList(ListNode head) {
            return mergeSort( head);
        }
    }



  • 相关阅读:
    金融系列7《动态数据认证》
    PHP异常处理详解
    C语言中的宏定义
    PHP SOCKET编程
    yii实现级联下拉菜单
    AR的一些常见的操作
    IP地址的三种表示格式及在Socket编程中的应用
    时间管理
    socket阻塞与非阻塞,同步与异步、I/O模型
    程序人生 PHP工程师
  • 原文地址:https://www.cnblogs.com/yutingliuyl/p/7009667.html
Copyright © 2011-2022 走看看