LeetCode 23:Merge k Sorted Lists 解题与思考
题目描述
将若干个有序数列合并成一个,简单点说就是归并排序的第二步
思路
很显然,只需要对所有数列的头部进行遍历,每遍历一次取出最值就好。
当然,作为通过率较低的hard题目,其需要考虑的情况也不少。
我最先想到的是需要判断数列顺序的升降序,结果没能ac,因为leetcode还特别喜欢测试空数组的情况。不过只要好好考虑了这些情况,剩下的就很好办了。
算法
1、先判断数列空的情况
2、倘若数列不为空,则寻找至少两个或以上数字的数列,判断升降序
3、依次遍历每个数组的头部,找到最大(小)值输出。
代码
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
ListNode* result = NULL, *current;
if ( lists.size() == 0 )return result;
int nowVal, nowPos;
bool decending;
for ( auto i : lists ) {
if ( i != NULL && i->next != NULL ) {
if ( i->val > i->next->val ) {
decending = true;
break;
}
if ( i->val < i->next->val ) {
decending = false;
break;
}
}
}
if ( decending ) {
nowVal = -100000;
nowPos = -1;
int pos = 0;
for ( auto i : lists ) {
if ( (i != NULL) && (i->val > nowVal) ) {
nowVal = i->val;
nowPos = pos;
}
pos++;
}
if ( nowPos == -1 )return result;
result = lists.at(nowPos);
lists.at(nowPos) = lists.at(nowPos)->next;
current = result;
while ( true ) {
nowVal = -100000;
nowPos = -1;
int pos = 0;
for ( auto i : lists ) {
if ( (i != NULL) && (i->val > nowVal) ) {
nowVal = i->val;
nowPos = pos;
}
pos++;
}
if ( nowPos == -1 )return result;
current->next = lists.at(nowPos);
lists.at(nowPos) = lists.at(nowPos)->next;
current = current->next;
}
}
else {
nowVal = 100000;
nowPos = -1;
int pos = 0;
for ( auto i : lists ) {
if ( (i != NULL) && (i->val < nowVal) ) {
nowVal = i->val;
nowPos = pos;
}
pos++;
}
if ( nowPos == -1 )return result;
result = lists.at(nowPos);
lists.at(nowPos) = lists.at(nowPos)->next;
current = result;
while ( true ) {
nowVal = 100000;
nowPos = -1;
int pos = 0;
for ( auto i : lists ) {
if ( (i != NULL) && (i->val < nowVal) ) {
nowVal = i->val;
nowPos = pos;
}
pos++;
}
if ( nowPos == -1 )return result;
current->next = lists.at(nowPos);
lists.at(nowPos) = lists.at(nowPos)->next;
current = current->next;
}
}
return result;
}
};
思考
还是稍微有点懒了,很多代码部分没有做优化,部分地方复制粘贴,其实代码可以更省些的。不过反正题目也不难,所以也不打算花太多时间在上面了。
leetcode真的是喜欢空输入这个极端状况啊,只要有机会就会弄个这个玩意儿卡一下你,有点伤脑筋。