首页 > 代码库 > leetcode__Merge k Sorted Lists

leetcode__Merge k Sorted Lists

Merge k Sorted Lists

 Total Accepted: 9746 Total Submissions: 41674My Submissions

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) {
        int len = lists.size();
        ListNode *p[len];
        ListNode *head = NULL;
        ListNode *l = NULL;
        
        while(true){
            int index = -1;
            int min = INT_MAX;
            
            for(int i=0;i<len;i++){
                if(lists[i] && lists[i]->val < min){
                    index =i;
                    min = lists[i]->val;
                }
            }
            
            if(min == INT_MAX){
                break;
            }
            
            lists[index] = lists[index]->next;
            
            if(!head){
                head = new ListNode(min);
                l = head;
            }else{
                l->next = new ListNode(min);
                l = l->next;
            }
        }
        
        return head;
    }
};