zoukankan      html  css  js  c++  java
  • 28-Merge Two Sorted Lists

    easy
    21. Merge 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.
    思路:利用map映射,值->指针集合,然后按值从小到大将指针链接起来。时间复杂度O(m+n),空间O(m+n)

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
            map<int,vector<ListNode*> > maps;
            push_into_map(l1,maps);
            push_into_map(l2,maps);
            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;
        }
        void push_into_map(ListNode* l,map<int,vector<ListNode*> > &maps)
        {
            while(l!=NULL)
            {
                maps[l->val].push_back(l);
                l= l->next;
            }
        }
    };
  • 相关阅读:
    .net core2.2
    9_山寨系统调用 SystemCallEntry
    7_API调用
    8_InlineHook
    6_再次开中断STI的正确姿势
    5_中断现场下
    4_中断现场中
    3_中断现场上
    2_多核复杂性
    1_中断提权
  • 原文地址:https://www.cnblogs.com/freeopen/p/5482955.html
Copyright © 2011-2022 走看看