148. Sort List [LeetCode]

版权声明:QQ:872289455. WeChat:luw9527. https://blog.csdn.net/MC_007/article/details/80869842

单链表的归并排序,常数空间,O(nlogn).

先来看几个简单的链表排序问题。


88Merge Sorted Array

Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

Note:

  • The number of elements initialized in nums1 and nums2 are m and n respectively.
  • You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.

Example:

Input:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6],       n = 3

Output: [1,2,2,3,5,6]

对两个排好序的数组进行归并排序,假设nums1足够大,足够容纳两个数组的所有元素。把排序好的元素存入nums1,从后往前填入nums1,不能从前往后,没法操作,会覆盖元素,除非另开辟一个空间。

class Solution {
public:
     void merge(vector < int >& nums1, int m, vector < int >& nums2, int n) {
         int ia = m - 1, ib = n - 1, cur = m + n - 1;
         while (ia >= 0 && ib >= 0)
            nums1[cur --] = nums1[ia] >= nums2[ib] ? nums1[ia --] : nums2[ib --];

         while (ib >= 0)
            nums1[cur --] = nums2[ib --];

    }
};


21Merge Two Sorted Lists

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

归并排序两个链表,链表已排好序,把两个链表拼接到一起。

下面几个比较复杂的题都可以经过灵活的转换,转换为这个问题。

这是最基本的一个函数,但是可以应对很多其他应用场景。


class Solution {
public:
    ListNode * mergeTwoLists(ListNode * l1, ListNode * l2) {
         if (l1 == nullptr) return l2;
         if (l2 == nullptr) return l1;

        ListNode dummy( - 1);
        ListNode *p = &dummy;

         while (l1 &&l2) {
             if (l1-> val >= l2-> val) {
                p-> next = l2;
                l2 = l2-> next;
            } else {
                p-> next = l1;
                l1 = l1-> next;
            }
            p = p-> next;
        }
         //指向剩余的部分
        p-> next = l1 ? l1 : l2;
         return dummy. next;
    }
};


23Merge k Sorted Lists

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

Example:

Input:
[
  1->4->5,
  1->3->4,
  2->6
]
Output: 1->1->2->3->4->4->5->6
对k个链表归并排序,转化为两两归并的问题。

class Solution {
public:
    ListNode * mergeKLists(vector <ListNode *>& lists) {
         if (lists. size() == 0) return nullptr;

        ListNode *p = lists[ 0];
         //从上到下滚雪球
         for ( int i = 1; i != lists. size(); ++i)
            p = mergeTwoLists(p, lists[i]);
         return p;
    }
    ListNode * mergeTwoLists(ListNode *l1, ListNode *l2) {
        ListNode dummy( - 1);
        ListNode *p = &dummy;
         while (l1 &&l2) {
             if (l1-> val >= l2-> val) {
                p-> next = l2;
                l2 = l2-> next;
            }
             else {
                p-> next = l1;
                l1 = l1-> next;
            }
            p = p-> next;
        }

        p-> next = l1 ? l1 : l2;
         return dummy. next;
    }
};




148Sort 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

归并排序单链表,最关键的两点:对折链表,然后merge这断开的两端链表。

class Solution {
public:
    ListNode * sortList(ListNode * head) {
         if (head == nullptr || head-> next == nullptr) return head;

        ListNode *fast = head;
        ListNode *slow = head;

         while (fast-> next &&fast-> next-> next) {
            fast = fast-> next-> next;
            slow = slow-> next;
        }

         //ListNode*leftend = slow;
        ListNode *l2begin = slow-> next;
        slow-> next = nullptr;

        ListNode *l1 = sortList(head);
        ListNode *l2 = sortList(l2begin);

         return mergeTwoList(l1, l2);
    }
    ListNode * mergeTwoList(ListNode *l1, ListNode *l2) {
        ListNode dummy( - 1);
        ListNode *p = &dummy;
         while (l1 &&l2) {
             if (l1-> val >= l2-> val) {
                p-> next = l2;
                l2 = l2-> next;
            } else {
                p-> next = l1;
                l1 = l1-> next;
            }
            p = p-> next;
        }

        p-> next = l1 ? l1 : l2;
         return dummy. next;
    }
};




桶排序的链表实现形式也可以结合链表归并排序:

我这个实现形式是把数据装入到桶里面,一个桶即是一个有序链表,每个桶的大小(链表长度)不超过100,桶的个数为a.size()/100,当然除以200,500都是可以的,经过我的测试(数据规模为50000),发现100和200的时候最佳.数据装入桶的时候要保证有序插入,最后把这些有序链表merge一下就可以了:

//桶排序
//struct ListNode {
//  int val;
//  ListNode *next;
// ListNode() : val(-1), next(NULL) {}
//  ListNode(int x) : val(x), next(nullptr) {}
//  ListNode(int x, ListNode *p) : val(x), next(p) {}
//};
//插入链表,保证有序
ListNode * insert(ListNode *head, int _val) {
    ListNode dummy( - 1);
    dummy. next = head;
    ListNode *newNode = new ListNode(_val);
    
    ListNode *pre = &dummy;
    ListNode *cur = head;

     while (cur &&_val >= cur-> val) {
        pre = cur;
        cur = cur-> next;
    }

    newNode-> next = cur;
    pre-> next = newNode;

     return dummy. next;
}

ListNode * mergeTwoLists(ListNode * l1, ListNode * l2) {
     if (l1 == nullptr) return l2;
     if (l2 == nullptr) return l1;

    ListNode dummy( - 1);
    ListNode *p = &dummy;

     while (l1 &&l2) {
         if (l1-> val >= l2-> val) {
            p-> next = l2;
            l2 = l2-> next;
        } else {
            p-> next = l1;
            l1 = l1-> next;
        }
        p = p-> next;
    }
     //指向剩余的部分
    p-> next = l1 ? l1 : l2;
     return dummy. next;
}

void bucketSort(vector < int >&a) {
     int BUCKET_NUM = 1 +a. size() / 100;
     //初始化BUCKET_NUM个桶,
    vector <ListNode *>buckets;
    ListNode *p = new ListNode[BUCKET_NUM];   
     for ( int i = 0; i != BUCKET_NUM; ++i)
        buckets. push_back( &p[i]);

     for ( int i = 0; i != a. size(); ++i) {
         int index = a[i] / 100;
        ListNode *head = buckets[index];
        buckets[index] = insert(head, a[i]);
    }

     //删除表头-1的节点
     for ( int i = 0; i != BUCKET_NUM; ++i) {
        buckets[i] = buckets[i]-> next;
    }

    ListNode *merge = buckets[ 0];
     for ( int i = 1; i != BUCKET_NUM; ++i) {
        merge = mergeTwoLists(merge, buckets[i]);
    }

     for ( int i = 0; i != a. size(); ++i) {
        a[i] = merge-> val;
        merge = merge-> next;
    }
}


其他排序方法参考我的另一篇博客:排序算法总结

猜你喜欢

转载自blog.csdn.net/MC_007/article/details/80869842