• [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
  • 相关阅读:
    atcoder #082 E 暴力 计算几何
    LightOJ 1364 树形DP
    gym100712 ACM Amman Collegiate Programming Contest
    CF757 C hash
    CF844 C 置换 水
    CF544 C 背包 DP
    CF540 D 概率 DP
    CF540 C BFS 水
    CF540 B 贪心
    CF745 C 并查集
  • 原文地址:https://www.cnblogs.com/freeneng/p/3099553.html
Copyright © 2020-2023  润新知