当前位置: 首页 > news >正文

[LeetCode] 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

给一个链表排序,要求Time: O(nlogn), constant space complexity.

解法:1. 把链表从中间分开Break the list to two in the middle.  2. 递归排序两个子链表Recursively sort the two sub lists.  3. 合并子链表Merge the two sub lists. 

解法:归并排序。由于有时间和空间复杂度的要求。把链表从中间分开,递归下去,都最后两个node时开始合并,返回上一层继续合并,直到结束。找中间点的方法可以用快慢指针,快指针走2步,慢指针走1步。也可以求出链表长度,再分开链表

Java:

public class Solution {
    public ListNode sortList(ListNode head) {
        if (head == null || head.next == null) return head;
        ListNode slow = head, fast = head, pre = head;
        while (fast != null && fast.next != null) {
            pre = slow;
            slow = slow.next;
            fast = fast.next.next;
        }
        pre.next = null;
        return merge(sortList(head), sortList(slow));
    }
    public ListNode merge(ListNode l1, ListNode l2) {
        ListNode dummy = new ListNode(-1);
        ListNode cur = dummy;
        while (l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                cur.next = l1;
                l1 = l1.next;
            } else {
                cur.next = l2;
                l2 = l2.next;
            }
            cur = cur.next;
        }
        if (l1 != null) cur.next = l1;
        if (l2 != null) cur.next = l2;
        return dummy.next;
    }
}

Java:

public class Solution {
    public ListNode sortList(ListNode head) {
        if (head == null || head.next == null) return head;
        ListNode slow = head, fast = head, pre = head;
        while (fast != null && fast.next != null) {
            pre = slow;
            slow = slow.next;
            fast = fast.next.next;
        }
        pre.next = null;
        return merge(sortList(head), sortList(slow));
    }
    public ListNode merge(ListNode l1, ListNode l2) {
        if (l1 == null) return l2;
        if (l2 == null) return l1;
        if (l1.val < l2.val) {
            l1.next = merge(l1.next, l2);
            return l1;
        } else {
            l2.next = merge(l1, l2.next);
            return l2;
        }
    }
}

Python:

class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

    def __repr__(self):
        if self:
            return "{} -> {}".format(self.val, repr(self.next))

class Solution:
    # @param head, a ListNode
    # @return a ListNode
    def sortList(self, head):
        if head == None or head.next == None:
            return head

        fast, slow, prev = head, head, None
        while fast != None and fast.next != None:
            prev, fast, slow = slow, fast.next.next, slow.next
        prev.next = None

        sorted_l1 = self.sortList(head)
        sorted_l2 = self.sortList(slow)

        return self.mergeTwoLists(sorted_l1, sorted_l2)

    def mergeTwoLists(self, l1, l2):
        dummy = ListNode(0)

        cur = dummy
        while l1 != None and l2 != None:
            if l1.val <= l2.val:
                cur.next, cur, l1 = l1, l1, l1.next
            else:
                cur.next, cur, l2 = l2, l2, l2.next

        if l1 != None:
            cur.next = l1
        if l2 != None:
            cur.next = l2

        return dummy.next

if __name__ == "__main__":
    head = ListNode(3)
    head.next = ListNode(4)
    head.next.next = ListNode(1)
    head.next.next.next= ListNode(2)
    print(Solution().sortList(head))  

C++:

class Solution {
public:
    ListNode* sortList(ListNode* head) {
        if (!head || !head->next) return head;
        ListNode *slow = head, *fast = head, *pre = head;
        while (fast && fast->next) {
            pre = slow;
            slow = slow->next;
            fast = fast->next->next;
        }
        pre->next = NULL;
        return merge(sortList(head), sortList(slow));
    }
    ListNode* merge(ListNode* l1, ListNode* l2) {
        ListNode *dummy = new ListNode(-1);
        ListNode *cur = dummy;
        while (l1 && l2) {
            if (l1->val < l2->val) {
                cur->next = l1;
                l1 = l1->next;
            } else {
                cur->next = l2;
                l2 = l2->next;
            }
            cur = cur->next;
        }
        if (l1) cur->next = l1;
        if (l2) cur->next = l2;
        return dummy->next;
    }
};

C++:

class Solution {
public:
    ListNode* sortList(ListNode* head) {
        if (!head || !head->next) return head;
        ListNode *slow = head, *fast = head, *pre = head;
        while (fast && fast->next) {
            pre = slow;
            slow = slow->next;
            fast = fast->next->next;
        }
        pre->next = NULL;
        return merge(sortList(head), sortList(slow));
    }
    ListNode* merge(ListNode* l1, ListNode* l2) {
        if (!l1) return l2;
        if (!l2) return l1;
        if (l1->val < l2->val) {
            l1->next = merge(l1->next, l2);
            return l1;
        } else {
            l2->next = merge(l1, l2->next);
            return l2;
        }
    }
};

  

  

All LeetCode Questions List 题目汇总

 

 

转载于:https://www.cnblogs.com/lightwindy/p/9572544.html

相关文章:

  • 室内空气节能净化之王
  • Elastic Stack-Elasticsearch使用介绍(一)
  • Linux 抓取网页方式(curl+wget)
  • 案例_(单线程)使用正则的内涵段子爬虫
  • flash沙盘预测试性能
  • MYSQL 配置文件
  • 【iOS-Cocos2d游戏开发】cocos2d 坐标系使用
  • bzoj5281/luogu4377 Talent Show (01分数规划+背包dp)
  • 纳米时代与现代无穷小分析
  • arguments.callee的作用及替换方案
  • 【IOS】实现一种书本的展示特效
  • asp.net webform设计思路的思考
  • 给自己的应用添加iAd广告之一
  • virsh查看迁移信息的两个命令
  • 【iOS-Cocos2d游戏开发】触屏事件处理机制
  • @jsonView过滤属性
  • [译] 理解数组在 PHP 内部的实现(给PHP开发者的PHP源码-第四部分)
  • Android Studio:GIT提交项目到远程仓库
  • electron原来这么简单----打包你的react、VUE桌面应用程序
  • emacs初体验
  • JS基础篇--通过JS生成由字母与数字组合的随机字符串
  • js写一个简单的选项卡
  • Mithril.js 入门介绍
  • tab.js分享及浏览器兼容性问题汇总
  • Vue实战(四)登录/注册页的实现
  • 机器人定位导航技术 激光SLAM与视觉SLAM谁更胜一筹?
  • 基于webpack 的 vue 多页架构
  • 聊聊hikari连接池的leakDetectionThreshold
  • 3月7日云栖精选夜读 | RSA 2019安全大会:企业资产管理成行业新风向标,云上安全占绝对优势 ...
  • # 计算机视觉入门
  • %3cscript放入php,跟bWAPP学WEB安全(PHP代码)--XSS跨站脚本攻击
  • (02)Cartographer源码无死角解析-(03) 新数据运行与地图保存、加载地图启动仅定位模式
  • (cos^2 X)的定积分,求积分 ∫sin^2(x) dx
  • (SpringBoot)第七章:SpringBoot日志文件
  • (附源码)springboot家庭财务分析系统 毕业设计641323
  • (附源码)springboot炼糖厂地磅全自动控制系统 毕业设计 341357
  • (一)u-boot-nand.bin的下载
  • (转)Linux下编译安装log4cxx
  • (转)微软牛津计划介绍——屌爆了的自然数据处理解决方案(人脸/语音识别,计算机视觉与语言理解)...
  • **PHP二维数组遍历时同时赋值
  • .net图片验证码生成、点击刷新及验证输入是否正确
  • .net项目IIS、VS 附加进程调试
  • /ThinkPHP/Library/Think/Storage/Driver/File.class.php  LINE: 48
  • ::前边啥也没有
  • @javax.ws.rs Webservice注解
  • @JSONField或@JsonProperty注解使用
  • @property python知乎_Python3基础之:property
  • [16/N]论得趣
  • [ActionScript][AS3]小小笔记
  • [boost]使用boost::function和boost::bind产生的down机一例
  • [BUG] Authentication Error
  • [BZOJ 4129]Haruna’s Breakfast(树上带修改莫队)
  • [C#]科学计数法(scientific notation)显示为正常数字
  • [C++核心编程](四):类和对象——封装
  • [codeforces]Levko and Permutation