148. Sort List [LeetCode]

单链表的归并排序,常数空间,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

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

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

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

 

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
typedef struct ListNode NODE;

/
/
/// Approch 1:
NODE *mergeTwoLists(NODE *l1, NODE *l2) {
    if (NULL == l1) return l2;
    if (NULL == l2) return l1;
    
    NODE dummy;
    dummy.next = NULL;
    
    NODE *pos = &dummy;
    
    while (l1 && l2) {
        if (l1->val <= l2->val) {
            pos->next = l1;
            l1 = l1->next;
        } else {
            pos->next = l2;
            l2 = l2->next;
        }
        pos = pos->next;
    }
    pos->next = l1 ? l1 : l2;
    return dummy.next;
}

/
/
/// Approch 2: recursion 
NODE *mergeTwoLists(NODE *l1, NODE *l2){
    if (NULL == l1) return l2;
    if (NULL == l2) return l1;
    
    if (l1->val <= l2->val) {
        l1->next = mergeTwoLists(l1->next, l2);
        return l1;
    } else {
        l2->next = mergeTwoLists(l1, l2->next);
        return l2;
    }
}

 

 

 

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个链表归并排序,转化为两两归并的问题。

NODE *mergeKLists(NODE **lists, int listsSize){
    if (NULL == lists) return NULL;
    if (listsSize < 1) return NULL;

    for (int i = 1; i < listsSize; i++) 
        lists[i] = mergeTwoLists(lists[i-1], lists[i]);

    return lists[listsSize - 1];
}

 

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这断开的两端链表。

NODE *sortList(NODE *head){
    if (NULL == head || NULL == head->next) return head;
    
    NODE *slow = head;
    NODE *fast = head;
    while (fast->next && fast->next->next) {
        slow = slow->next;
        fast = fast->next->next;
    }
    NODE *l2begin = slow->next;
    slow->next = 0;
    // merge Lists must be sorted
    NODE *l1 = sortList(head);
    NODE *l2 = sortList(l2begin);

    return mergeTwoLists(l1, l2);
}

 

 

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

我这个实现形式是把数据装入到桶里面,一个桶即是一个有序链表,每个桶的大小(链表长度)不超过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;
    }
}
 

 

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

luuyiran

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值