zoukankan      html  css  js  c++  java
  • 13.Merge k Sorted Lists

        思路:利用map<int,vector<ListNode*> >
    做值和指针的映射,最后将指针按值依次链接起来,
    时间复杂度O(N),空间O(N)    
        Merge k sorted linked lists and
    return it as one sorted list. Analyze and describe its complexity.      
    
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
     /*
    
     */
    class Solution {
    public:
        ListNode* mergeKLists(vector<ListNode*>& lists) {
            map<int,vector<ListNode*> > maps;
            for(int i=0;i<lists.size();++i)
            {
                while(lists[i]!=NULL)
                {
                    maps[lists[i]->val].push_back(lists[i]);
                    lists[i] = lists[i]->next;
                }
            }
            ListNode *now=NULL,*pre=NULL,*head;
            map<int,vector<ListNode*> >::const_iterator it = maps.begin();
            if(it!=maps.end()){
                    head = (it->second)[0];
            }
            else head = NULL;
            while(it!=maps.end())
            {
                cout<<(it->second).size()<<endl;
                for(int k=0;k<(it->second).size();++k)
                {
                    pre = now;
                    now = (it->second)[k];
                    if(pre!=NULL)pre->next = now;
                }
                it++;
            }
            return head;
        }
    };
  • 相关阅读:
    TP自适应
    消息编解码Nanopb
    协程coroutine
    gui设计
    常用小工具集
    在github上新建一个仓库并上传本地工程
    通用定时器设计(2)
    通用定时器设计(1)
    嵌入式驱动程序设计
    meta标签的理解
  • 原文地址:https://www.cnblogs.com/freeopen/p/5483010.html
Copyright © 2011-2022 走看看