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

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

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode *mergeKLists(vector<ListNode *> &lists) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
            if(lists.size()==0)return NULL;
            int min,index;
             int i=0;
            for(;i<lists.size();i++){
                if(lists[i]!=NULL){
                    min=lists[i]->val;
                    index=i;
                    break;
                }
            }
            if(i==lists.size())return NULL;
            i++;
            if(i<lists.size())
            for(;i<lists.size();i++){
                if(lists[i]!=NULL&&lists[i]->val<min){
                    min=lists[i]->val;
                    index=i;
                }
            }
            ListNode* root=lists[index];
            lists[index]=lists[index]->next;
            ListNode* tail=root;
            while(true){
                int i=0;
                for(;i<lists.size();i++){
                    if(lists[i]!=NULL){
                        min=lists[i]->val;
                        index=i;
                        break;
                    }
                }
                if(i==lists.size())return root;
                i++;
                if(i<lists.size())
                for(;i<lists.size();i++){
                    if(lists[i]!=NULL&&lists[i]->val<min){
                        min=lists[i]->val;
                        index=i;
                    }
                }
                tail->next=lists[index];
                tail=tail->next;
                lists[index]=lists[index]->next;
            }
        }
    };
    
  • 相关阅读:
    文件
    购物车
    session
    三级联动
    综合
    jquery弹窗插件
    Jquery
    PDO
    session cookie用法
    租房子
  • 原文地址:https://www.cnblogs.com/superzrx/p/3322687.html
Copyright © 2011-2022 走看看