码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode__Merge k Sorted Lists

时间:2014-05-01 17:11:32      阅读:234      评论:0      收藏:0      [点我收藏+]

标签:leetcode

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;
    }
};






leetcode__Merge k Sorted Lists,码迷,mamicode.com

leetcode__Merge k Sorted Lists

标签:leetcode

原文地址:http://blog.csdn.net/xuerenlv123/article/details/24783057

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!