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

    原题链接http://oj.leetcode.com/problems/merge-k-sorted-lists/

    题目描述:

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

    题解:

      这是个典型的分治题,用递归,不断平分,解决merge两个有序链表的小问题即可。

     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 *merge(ListNode* A,ListNode* B){
    12         if(A==NULL && B==NULL)
    13             return NULL;
    14         if(A == NULL)
    15             return B;
    16         if(B == NULL)
    17             return A;
    18         ListNode *p = A;
    19         ListNode *q = B;
    20         ListNode *res = NULL;
    21         ListNode *pre = NULL;
    22         if(p->val<=q->val){
    23             res = p;
    24             p = p->next;
    25             pre = res;
    26         }else{
    27             res = q;
    28             q = q->next;
    29             pre = res;
    30         }
    31         while(p!=NULL && q!=NULL){
    32             if(p->val<=q->val){
    33                 pre->next = p;
    34                 pre = p;
    35                 p = p->next;
    36             }else{
    37                 pre->next = q;
    38                 pre = q;
    39                 q = q->next;
    40             }
    41         }
    42         while(p!=NULL){
    43             pre->next = p;
    44             pre = p;
    45             p = p->next;
    46         }
    47         while(q!=NULL){
    48             pre->next = q;
    49             pre = q;
    50             q = q->next;
    51         }
    52         pre->next = NULL;
    53         return res;
    54     }
    55     
    56     ListNode *mergeKLists(vector<ListNode *> &lists) {
    57         int size = lists.size();
    58         if(size == 0)
    59             return NULL;
    60         if(size == 1)
    61             return lists[0];
    62         vector<ListNode*> A,B;
    63         for(int i=0; i<size/2; i++){
    64             A.push_back(lists[i]);
    65         }
    66         for(int i=size/2; i<size; i++){
    67             B.push_back(lists[i]);
    68         }
    69         return merge(mergeKLists(A),mergeKLists(B));
    70     }
    71 };
  • 相关阅读:
    [转]spring学习笔记7.自动装配(补充)
    [转]JSON 入门指南
    [转]spring学习笔记补: 生命周期
    rownum的用法
    简易计算器实现
    Flush the AOS cache from code
    通过Batch发送Report
    Export excel file format
    The report's image auto resizes (Always use in report)
    Save the users last values in a dialog
  • 原文地址:https://www.cnblogs.com/codershell/p/3592992.html
Copyright © 2011-2022 走看看