zoukankan      html  css  js  c++  java
  • Merge k Sorted Lists [LeetCode]

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

    Summary:  Finds the smallest node every round, then links it to the one sorted list.

     1     ListNode *mergeKLists(vector<ListNode *> &lists) {
     2         ListNode * head = NULL;
     3         ListNode * pre_node = NULL;
     4         while(true){
     5             //find the smallest one
     6             ListNode * smallest_node = NULL;
     7             for(auto item : lists) {
     8                 if(item != NULL){
     9                     if(smallest_node == NULL || item->val < smallest_node->val )
    10                         smallest_node = item;
    11                 }
    12             }
    13             if(smallest_node == NULL)
    14                 break;
    15                 
    16             if(pre_node == NULL){
    17                 pre_node = smallest_node;
    18                 head = pre_node;
    19             }else{
    20                 pre_node -> next = smallest_node;
    21                 pre_node = pre_node -> next;
    22             }
    23             
    24             for(int i = 0; i< lists.size(); i ++){
    25                 if(lists[i] == smallest_node)
    26                     lists[i] = lists[i] -> next;
    27             }
    28         }
    29         return head;
    30     }
  • 相关阅读:
    php 1231
    php 1229
    php 1228
    php 0103
    php 1227
    php 1230
    php 0104
    flex弹性布局学习
    ps抠图的几种方法
    sql2005 不同的日期展示形式
  • 原文地址:https://www.cnblogs.com/guyufei/p/3410366.html
Copyright © 2011-2022 走看看