Leetcode 23. Merge k Sorted Lists

原题地址:https://leetcode.com/problems/merge-k-sorted-lists/description/

题目描述

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

意思很好懂,把k个有序链表合并成一个

思路

我的思路是就把这个当成归并排序里归并的那部分来实现

代码

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* merge(vector<ListNode*>& lists, int index1,int index2){
        if(lists[index1]==NULL && lists[index2]==NULL){
            return NULL;
        }
        if(lists[index1]==NULL){
            return lists[index2];
        }
        if(lists[index2]==NULL){
            return lists[index1];
        }
        ListNode * temp1 = lists[index1];
        ListNode * temp2 = lists[index2];
        ListNode * head;
        if(temp1->val > temp2->val){
            head = temp2;
            temp2=temp2->next;
        }else{
            head = temp1;
            temp1= temp1->next;
        }
        ListNode * current = head;
        while(temp1!=NULL && temp2 !=NULL){
            if(temp1->val > temp2-> val){
                current->next = temp2;
                current = current->next;
                temp2 = temp2->next;
            }else{
                current->next = temp1;
                current = current->next;
                temp1 = temp1->next;
            }
        }
        if(temp1!=NULL){
            current->next = temp1;
        }else{//temp2!=NULL
            current->next = temp2;
        }
        return head;   
    }
    
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        if(lists.empty()){
            return NULL;
        }
        if(lists.size()==1){
            return lists[0];
        }
        vector<ListNode*> new_lists;
        for(int i =0;i<lists.size();){
            ListNode * temp;
            if(i+1<lists.size()){
                temp = merge(lists,i,i+1);
            }else{
                temp = lists[i];
            }
            new_lists.push_back(temp);
            i+=2;
        }
        return mergeKLists(new_lists);
    }
};

踩坑

提交过程中有几次TLERuntime Error,TLE是因为merge函数里指针没处理好(赋值给head之后没有把temp移动到下一个元素,不过具体的情况我还是没想象清楚,先留着),RuntimeError是因为测试的例子里有的list是空的或者整个vector是空的没考虑到。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,354评论 0 33
  • LeetCode 刷题随手记 - 第一部分 前 256 题(非会员),仅算法题,的吐槽 https://leetc...
    蕾娜漢默阅读 18,158评论 2 36
  • 一直以来不断有各路盆友过来咨询想加入我一起做微商,蛋素,她们给我说的最多的一句话居然是:其实,我挺讨厌微商的。 其...
    Michelle兰兰阅读 1,878评论 0 1
  • 非常喜欢这幅画里的组合,湛蓝的天空飘逸着雪花。温暖的房子里蕴潤着烟火气息。大地无言,落雪无声,静谧安详的心。
    华枝春满5339阅读 4,316评论 9 17
  • 人生之路100阅读 845评论 0 0