• [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
  • 相关阅读:
    CVE-2019-16278:Nostromo Web服务器的远程命令执行
    内网渗透一(信息收集)
    Apache Flink 任意jar包上传漏洞
    Apache ---- Solrl漏洞复现
    linux内核过高导致vm打开出错修复脚本
    lvm拓展
    文件时间进度扫描控制,可回溯,空闲扫描,系统时间调整不影响
    Raid 管理
    curl 工具使用
    docker 入门
  • 原文地址:https://www.cnblogs.com/freeneng/p/3099553.html
Copyright © 2020-2023  润新知