首页 > 代码库 > leetcode__Merge k Sorted Lists
leetcode__Merge k Sorted Lists
Merge k Sorted Lists
Total Accepted: 9746 Total Submissions: 41674My SubmissionsMerge 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; } };
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。