lc 合并K个排序链表

链接:https://leetcode-cn.com/problems/merge-k-sorted-lists/

代码:

/**
 * 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 n = lists.size();
        if(n == 0) return nullptr;
        vector<ListNode*> curs;
        ListNode* res = new ListNode(-1);
        ListNode* last = res;
        for(int i = 0; i < n; i++) {
            if(lists[i]!=nullptr) curs.push_back(lists[i]);
        }
        while(1) {
            int m = curs.size();
            if(m == 0) break;
            // cout << m << endl;
            // ListNode* min_ptr = nullptr;
            int min_index = -1;
            int min_value = INT_MAX;
            for(int i = 0; i < m; i++) {
                if(min_value > curs[i]->val) {
                    min_value = curs[i]->val;
                    min_index = i;
                    
                }
            }
            last->next = new ListNode(min_value);
            last = last->next;
            curs[min_index] = curs[min_index]->next;
            if(curs[min_index] == nullptr) {
                curs.erase(curs.begin()+min_index);
            }
        }
        // cout << "40" << endl;
        return res->next;
    }
};
View Code

思路:K 路有序归并即可

posted on 2020-05-25 00:55  FriskyPuppy  阅读(131)  评论(0编辑  收藏  举报

导航