leetcode sort-list
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode sort-list相关的知识,希望对你有一定的参考价值。
题目描述
Sort a linked list in O(n log n) time using constant space complexity.
思路:时间复杂度为O(nlogn),空间复杂度为常数,用归并排序
在下的代码 时间1162ms 空间27696k
/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ import java.util.ArrayList; public class Solution { public ListNode sortList(ListNode head) { if(head==null||head.next==null){ return head; } ListNode mid = findMid(head); ListNode midNext = mid.next; mid.next = null; return mergeList(sortList(head), sortList(midNext)); } private ListNode mergeList(ListNode list1, ListNode list2) { ListNode head = new ListNode(0); ListNode cur = head; while (list1 != null && list2 != null) { if (list1.val <= list2.val){ cur.next = list1; list1 = list1.next; } else { cur.next = list2; list2 = list2.next; } cur = cur.next; } if (list1 != null) { cur.next = list1; } else if (list2 != null) { cur.next = list2; } return head.next; } private ListNode findMid(ListNode head){ if (head == null) return head; ListNode fast = head; ListNode slow = head; while (fast.next != null && fast.next.next != null) { fast = fast.next.next; slow = slow.next; } return slow; } }
以上是关于leetcode sort-list的主要内容,如果未能解决你的问题,请参考以下文章