首先无脑爆破,使用最直观的方法AC
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* mergeInBetween(ListNode* list1, int a, int b, ListNode* list2) {
ListNode* cur = list1,*prev = NULL,*tail = list2;
//find list2 last node
while(tail && tail->next)
tail = tail->next;
//find list1 node before delete
for(int i = 0;i < a;i++)
{
prev = cur;
cur = cur->next;
}
for(int i = a-1;i < b;i++)
{
cur= cur->next;
}
prev->next = list2;
tail->next = cur;
return list1;
}
};
运行效率
Runtime: 704 ms, faster than 5.01% of C++ online submissions for Merge In Between Linked Lists.
Memory Usage: 94.8 MB, less than 66.42% of C++ online submissions for Merge In Between Linked Lists.
仅仅比5.01%的C++代码快,看样子存在较大的优化空间。
简单看了下第一个循环里两条语句存在冗余,可以优化成一条语句,优化后的代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* mergeInBetween(ListNode* list1, int a, int b, ListNode* list2) {
ListNode* prev = list1,*tail = list2;
//find list2 last node
while(tail && tail->next)
tail = tail->next;
//find list1 node before delete
for(int i = 0;i < a - 1;i++)
{
prev = prev->next;
}
ListNode* cur = prev->next;
for(int i = a - 1;i < b;i++)
{
cur= cur->next;
}
prev->next = list2;
tail->next = cur;
return list1;
}
};
优化后的执行时间:
Runtime: 616 ms, faster than 11.55% of C++ online submissions for Merge In Between Linked Lists.
Memory Usage: 94.9 MB, less than 66.42% of C++ online submissions for Merge In Between Linked Lists.
优化提升不大,现在思考如何减少循环个数,合并循环,提升程序执行效率。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* mergeInBetween(ListNode* list1, int a, int b, ListNode* list2) {
ListNode* prev = list1,*last = list2,*tail = list1;
//find list2 last node
while(last && last->next)
last = last->next;
int count = 0;
while(tail && tail->next)
{
//find the (a-1)th node
if(count == a - 1)
prev = tail;
tail = tail->next;
//find the (b+1)th node
if(count++ == b)
break;
}
//a-1 ->next = list2, list2->b+1
prev->next = list2;
last->next = tail;
return list1;
}
};