zoukankan      html  css  js  c++  java
  • LeetCode: MergekSortedLists

    Title: 

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

    排好序的,然后merge,很容易让人联想到归并排序。可以将k个序列按照二分进行分割,然后当长度为1时返回一个排好序的序列,最后将两个序列merge

    class Solution{
    public:
        ListNode* merge(ListNode* list1, ListNode* list2){
            ListNode head(0),*tail = &head;
            while (list1 != NULL && list2 != NULL){
                if (list1->val < list2->val){
                    tail->next = list1;
                    tail = list1;
                    list1 = list1->next;
                }else{
                    tail->next = list2;
                    tail = list2;
                    list2 = list2->next;
                }
            }
            if (list1 != NULL){
                tail->next = list1;
            }
            if (list2 != NULL){
                tail->next = list2;
            }
            return head.next;
        }
        ListNode* divide(int l,int r,vector<ListNode* > &lists){
            int m = (l + r) / 2;
            if (l < r){
                return merge(divide(l,m,lists),divide(m+1,r,lists));
            }else
                return lists[l];
        }
        ListNode* mergeKLists(vector<ListNode* > &lists){
            int k = lists.size();
            if (0 == k)
                return NULL;
            return divide(0,k-1,lists);
        }
    };
  • 相关阅读:
    《大道至简》读后有感
    关于jQuery放置位置的问题01
    javascript基础
    层叠样式表与css3基础
    经典sql语句
    java开发中的23种设计模式
    struts2漏洞以及测试
    离开贴吧大概会写下博客吧
    Set介绍
    小知识点
  • 原文地址:https://www.cnblogs.com/yxzfscg/p/4427559.html
Copyright © 2011-2022 走看看