Sharing my C++ code with multimap for solving k sorted Lists


  • 0
    S
      ListNode  result(0);
      ListNode*  head = &result;
      multimap<int,ListNode*> tempMap;//键值可以重复
      //初始化,注意已对键值排序,键保存的是元素大小,值保存的当前元素的地址
      for(int i=0;i<lists.size();i++){
           if (lists[i]!=NULL)
    		   tempMap.insert(pair<int,ListNode*>(lists[i]->val,lists[i])); //常用的赋值技巧		       
      }	 
      //主循法
      while(tempMap.size()>0){
    	  //拼上最新的元素
    	  head->next = tempMap.begin()->second;
    	  head = head->next;
    
    	  //tempMap,删除旧值,插入新值,		
    	  tempMap.erase(tempMap.begin());
    	  if(head->next!=NULL)//不为空才插入
    	  tempMap.insert(pair<int,ListNode*>(head->next->val,head->next)); 		       
      }	 
      return  result.next;

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.