排序链表
在 O(n log n) 時間復雜度和常數級空間復雜度下,對鏈表進行排序。
示例 1:
輸入: 4->2->1->3 輸出: 1->2->3->4 復制代碼示例 2:
輸入: -1->5->3->4->0 輸出: -1->0->3->4->5 復制代碼 /*** 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 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;}l2.next = merge( l1 , l2.next );return l2;} } 復制代碼解題思路: 題目要求時間復雜度nlogn ,則需要使用快排或者歸并排序 , 因為是鏈表 , 可以采用歸并 , 對鏈表進行對半短鏈 ,斷到單節點 , 然后進行歸并 ,最后返回
總結
- 上一篇: 【监控】Grafana面板修改记录
- 下一篇: maven 安装