leetcode 27: Merge k Sorted Lists

本文详细阐述了如何将多个已排序的链表合并为一个有序链表的方法,通过使用最小堆来优化过程,确保了高效性和简洁性。包括代码实现和复杂度分析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


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

keypoints: 1 be familiar with use of pointer to pointer ** pre, no need for a dummy head node.

2. when the container need erase or insert, it's probably a sign of using list instead of vector.

3. when use erase or insert function in vector and list, the argument must be iterator not index. Whereas, the argument is index position in string class.

[思路]

每个list的第一个数,是当前list的最小值. 所有lists第一个值中的最小值为所剩下数中的最小值. 

维持一个min heap, 每个element是 所有list的头指针. 最小值对应的头指针在heap的顶部. 取出val=min的头指针, 并将下一个元素插入heap中. 即可.

[code]

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        //init check
        if(lists==null || lists.length==0) return null;
        
        int k = lists.length;
        PriorityQueue<ListNode> minHeap = new PriorityQueue<ListNode>(k, new Comparator<ListNode>(){
            @Override
            public int compare(ListNode n1, ListNode n2) {
                return n1.val - n2.val;
            }
        });
        
        for(int i=0; i<k; i++) {
            if(lists[i] != null) minHeap.add(lists[i]);
        }
        
        ListNode dummy = new ListNode(0);
        ListNode p = dummy;
        
        while(!minHeap.isEmpty()) {
            ListNode min = minHeap.remove();
            if(min.next!=null) minHeap.add(min.next);
            p.next = min;
            p = p.next;
        }
        return dummy.next;
    }
}


<不用heap的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) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        //if( lists.size() <= 1) return intervals; 
        list<ListNode* > mylist;
        
        for( int i=0; i< lists.size(); i++){
            if(lists[i] != NULL) {
                mylist.push_back( lists[i] );
            }
        }
        
        ListNode * head = NULL;
        ListNode ** pre = &head;
        
        while( ! mylist.empty()) {
            list<ListNode* > :: iterator minIt = mylist.begin();
            list<ListNode* > :: iterator it = mylist.begin();
            
            while( ++it != mylist.end() ) {                
                if( (*it)->val < (*minIt)->val ) {
                    minIt = it;
                }
            }
            
            *pre = *minIt;
            if( (*minIt)->next == NULL ) {
                mylist.erase( minIt );
            } else {
                (*minIt) = (*minIt)->next ;
            }
            pre = &( (*pre)->next);     
        }
        return head;
    }
};


/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    
//null, {}, {{1},{2,3}}    
    public ListNode mergeKLists(ArrayList<ListNode> lists) {
        // Start typing your Java solution below
        // DO NOT write main() function
        //check input.
        if(lists==null) return null;
        
        ListNode head = new ListNode(0); //dummy
        ListNode p = head;
        ArrayList<ListNode> temp = new ArrayList<ListNode>();
        
        for(int i=0; i<lists.size(); i++) {
            if(lists.get(i)!=null) {
                temp.add( lists.get(i) );
            }
        }
        
        while( !temp.isEmpty() ) {
            int min = temp.get(0).val;
            ListNode minNode = temp.get(0);
            int minIndex = 0;
            for(int i=1; i<temp.size(); i++) {
                if(min > temp.get(i).val) {
                    minNode = temp.get(i);
                    min = minNode.val;
                    minIndex = i;
                }
            }
            p.next = minNode;
            p = p.next;
            
            if(minNode.next ==null) {
                temp.remove(minIndex);
            } else {
                temp.set(minIndex, minNode.next);  //<strong>big mistake!!! if you wanna change the elment in list must use list.set().</strong>
            }
        }
        
        return head.next;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值