[LintCode] Sort List [分治]

news/2024/6/22 23:45:01

Problem

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

Example

Given 1-3->2->null, sort it to 1->2->3->null.

Note

这道题目可以用分治法来做,首先从链表中点分割链表,然后将两个链表重新排序并合并。

Solution

public class Solution {
    public ListNode sortList(ListNode head) {  
        if (head == null || head.next == null) return head;
        ListNode mid = findMid(head);
        ListNode n2 = sortList(mid.next);
        mid.next = null;
        ListNode n1 = sortList(head);
        return merge(n1, n2);
    }
    public ListNode findMid(ListNode head) {
        ListNode slow = head, fast = head.next;
        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }
        return slow;
    }
    public ListNode merge(ListNode n1, ListNode n2) {
        ListNode dummy = new ListNode(0);
        ListNode head = dummy;
        while (n1 != null && n2 != null) {
            if (n1.val < n2.val) {
                head.next = n1;
                n1 = n1.next;
            }
            else {
                head.next = n2;
                n2 = n2.next;
            }
            head = head.next;
        }
        if (n1 != null) head.next = n1;
        else head.next = n2;
        return dummy.next;
    }
}

http://www.niftyadmin.cn/n/2211979.html

相关文章

安全事件标准化

2019独角兽企业重金招聘Python工程师标准>>> 安全事件标准化 一般的日志系统,为了接收日志的效率&#xff0c;不去做日志的标准化工作&#xff0c;收集大量冗余日志在数据库&#xff0c;而庞大的数据库在检索时导致效率越来越低&#xff0c;更别提自动扫选出故障。…

pku oj overhang叠加卡片求最少的卡片数

这个估计是里面第二简单的了&#xff0c;因为第一简单的是求ab 哈哈&#xff0c;一submit就ac了 题目如下&#xff1a; Description How far can you make a stack of cards overhang a table? If you have one card, you can create a maximum overhang of half a card lengt…

python小demo之判断闰年

#_*_ codingutf-8 __author__ kysida #定义函数 def leap_year(year):if year % 4 0:if (year / 100) % 4 0:return "the year is a leap year"return "the year is not a leap year" #主程序 if __name__ __main__:year int(raw_input("Please …

用mysql工具导数据_MySQL导入导出数据mysqldump工具的基本用法及mysql的备份总结

导出要用到MySQL的mysqldump工具&#xff0c;基本用法是&#xff1a;shell> mysqldump [OPTIONS] database [tables]如果你不给定任何表&#xff0c;整个数据库将被导出。通过执行mysqldump --help&#xff0c;你能得到你mysqldump的版本支持的选项表。注意&#xff1a;如果…

转 Linux命令-文件管理命令

http://jingyan.baidu.com/article/9113f81bc1c7a72b3214c7d3.html Linux命令-文件管理命令 浏览&#xff1a;4118|更新&#xff1a;2012-11-12 15:26|标签&#xff1a;linux linux系统因其优秀的稳定性和安全性&#xff0c;被越来越多的企业服务器应用。随之而来的越来越多的人…

python 基础知识梳理——迭代器和生成器

引言 for i in [1,2,3,4,5,6]:print(i)这是一个非常简单的for in语句&#xff0c;什么样的对象可以被用来迭代呢&#xff1f; 容器、可迭代对象、迭代器 在Python中一切皆是对象&#xff0c;对象的抽象就是类&#xff0c;而对象的集合就是容器。 列表list:[0,1,2]&#xff…

02-、java01-File类、递归

01、这是进阶java的博客总结&#xff0c;有各种课程的学习总结和代码总结&#xff0c;以后再做一个自己的工具箱博客总结&#xff0c;希望大家努力学习加油呀 02、File类 --除了 java.lang[主要是各种基本类型&#xff0c;不需要导入] java.util[各种基础工具&#xff0c;需要…