• 【Lintcode】098.Sort List


    题目:

    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.

    题解:

      O(n log n) : 快速排序,归并排序,堆排序

    Solution 1 ()

    class Solution {
    public:
        ListNode *sortList(ListNode *head) {
            if (!head || !head->next) {
                return head;
            }
            
            ListNode* slow = head;
            ListNode* fast = head->next;
            
            while (fast && fast->next) {
                slow = slow->next;
                fast = fast->next->next;
            }
            ListNode* right = sortList(slow->next);
            slow->next = nullptr;
            ListNode* left = sortList(head);
            
            return merge(left, right);
        }
        
        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;
        }
    };

    Solutin 2 ()

    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;
            }                                         
        }
    };
  • 相关阅读:
    spark streaming 整合kafka(二)
    JAVA设计模式之动态代理
    使用org.apache.commons.cli包来设计JAVA命令行工具
    HTML教程
    Java InputStream和Reader
    Java IO
    程序员怎么把自己的招牌打出去?
    Java设计模式之单例模式
    JAVA NIO
    Java文件流字节流和字符流的区别
  • 原文地址:https://www.cnblogs.com/Atanisi/p/6848162.html
Copyright © 2020-2023  润新知