zoukankan      html  css  js  c++  java
  • [Leetcode 50] 23 Merge K Sorted Lists

    Problem:

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

    Analysis:

    Since each list is sorted, the second element won't be merged into the final list until the first element is merged. So we can scan the head of each list and find the minimum element to merge into the final result. Note how to process those empty list and when to exit the scan phase.

    Code:

     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     ListNode *next;
     6  *     ListNode(int x) : val(x), next(NULL) {}
     7  * };
     8  */
     9 class Solution {
    10 public:
    11     ListNode *mergeKLists(vector<ListNode *> &lists) {
    12         // Start typing your C/C++ solution below
    13         // DO NOT write int main() function
    14         if (lists.size() == 0) return NULL;
    15         
    16         ListNode *head=NULL, *cur=NULL;
    17         int  minIdx;
    18         while (true) {
    19             minIdx = -1;
    20             for (int i=0; i<lists.size(); i++) {
    21                 if (lists[i] != NULL) {
    22                     if (minIdx == -1) 
    23                         minIdx = i;
    24                     else if (lists[i]->val < lists[minIdx]->val) {
    25                         minIdx = i;
    26                     }
    27                 }
    28             }
    29             
    30             if (minIdx == -1) break; //all list are NULL;
    31             
    32             if (head == NULL) {
    33                 head = lists[minIdx];
    34                 cur = lists[minIdx];
    35             } else {
    36                 cur->next = lists[minIdx];
    37                 cur = cur->next;
    38             }
    39             
    40             lists[minIdx] = lists[minIdx]->next;
    41         }
    42         
    43         return head;
    44     }
    45 };
    View Code
  • 相关阅读:
    TCP协议详解-IPv4
    welcome to my cnblog
    怎样解决闭包造成的内存泄漏
    跳转路由后请求失败
    vant grid组件图片加载问题
    3次握手
    res.send()传参----Invalid status code: 1
    堆栈总结
    jQuery实现全选
    phpstudy_pro打开MySQL服务,一闪一闪的
  • 原文地址:https://www.cnblogs.com/freeneng/p/3099553.html
Copyright © 2011-2022 走看看