zoukankan      html  css  js  c++  java
  • LeetCode——merge-k-sorted-lists

    Question

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

    Solution

    1. 归并排序中的Merge过程。

    2. 时间复杂度: 节点数目*k

    Code

    /**
     * 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) {
            int size = lists.size();
            if (size == 0)
                return NULL;
            if (size == 1)
                return lists[0];
            ListNode* head = new ListNode(-1);
            ListNode* pNode = head;
            while (1) {
                bool flag = false;
                int index;
                int cur = INT_MAX;
                for (int i = 0; i < size; i++) {
                    if (lists[i] != NULL) {
                        flag = true;
                        if (lists[i]->val < cur) {
                            cur = lists[i]->val;
                            index = i;
                        }
                    }
                }
                if (flag == false)
                    break;
                pNode->next = lists[index];
                pNode = lists[index];
                lists[index] = lists[index]->next;
            }
            return head->next;
        }
    };
    
  • 相关阅读:
    Linux 文件特殊权限
    Linux ACL权限
    Linux 用户管理命令
    Asm.js: Javascript的编译目标
    《Zero to One》的一些读书笔记
    Tomcat架构(四)
    Tomcat架构(三)
    Tomcat架构(二)
    Tomcat 架构 (一)
    MATERIAL DESIGN学习笔记
  • 原文地址:https://www.cnblogs.com/zhonghuasong/p/7766679.html
Copyright © 2011-2022 走看看