这道题目我真是无语。
不知道判题程序是怎么判断TLE
的。
下面我贴出我的测试程序,两个解决方案,经过10次测试,消耗的时间.
方案1 是TLE
的方案,方案2 是AC
的方案
代码
//
// main.cpp
// test
//
// Created by 小康 on 20/11/2018.
// Copyright © 2018 小康. All rights reserved.
//
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* a[100005];
void reorderList(ListNode* head) {
if(head ==NULL ||head->next==NULL) return;
ListNode* iter = head;
ListNode* iter2 = head;
int tag=0;
ListNode* term;
int pos =0;
while(iter2&&iter2->next)
{
a[tag++]=iter;
iter=iter->next;
iter2 = iter2->next->next;
}
if(iter2)
term = a[tag-1]->next->next;
else
term = a[tag-1]->next;
ListNode* temp;
for(int i=tag-1;i>=0;i--)
{
temp = term;
term = term->next;
temp->next=a[i]->next;
a[i]->next = temp;
}
}
};
class Solution2 {
public:
ListNode* a[100005];
void reorderList(ListNode* head) {
if(head ==NULL ||head->next==NULL) return;
ListNode* iter = head;
ListNode* iter2 = head;
int tag=0;
ListNode* term;
int pos =0;
while(iter2&&iter2->next)
{
a[tag++]=iter;
iter=iter->next;
iter2 = iter2->next->next;
}
term = a[tag-1]->next;
if(iter2==NULL) tag--;
ListNode* temp;
for(int i=tag-1;i>=0;i--)
{
temp = term->next;
term->next = temp->next;
temp->next =a[i]->next;
a[i]->next = temp;
}
}
};
int main() {
clock_t start,end;
int i=0;
while(i<10){
cout<<i<<endl;
start = clock();
ListNode* head = new ListNode(1);
head->next = new ListNode(2);
head->next->next = new ListNode(3);
head->next->next->next = new ListNode(4);
Solution* s = new Solution();
s->reorderList(head);
end = clock();
double dur = (double)(end - start);
printf("Use Time1 :%f ",dur);
start = clock();
ListNode* head2 = new ListNode(1);
head2->next = new ListNode(2);
head2->next->next = new ListNode(3);
head2->next->next->next = new ListNode(4);
Solution2* s2 = new Solution2();
s2->reorderList(head2);
end = clock();
double dur2 = (double)(end - start);
printf("Use Time2 :%f\n",dur2);
i++;
}
}
测试结果:
0
Use Time1 :368.000000 Use Time2 :367.000000
1
Use Time1 :396.000000 Use Time2 :337.000000
2
Use Time1 :405.000000 Use Time2 :386.000000
3
Use Time1 :339.000000 Use Time2 :405.000000
4
Use Time1 :363.000000 Use Time2 :383.000000
5
Use Time1 :351.000000 Use Time2 :371.000000
6
Use Time1 :332.000000 Use Time2 :335.000000
7
Use Time1 :388.000000 Use Time2 :345.000000
8
Use Time1 :361.000000 Use Time2 :367.000000
9
Use Time1 :347.000000 Use Time2 :372.000000
Program ended with exit code: 0
根本就没什么差距,可是LeetCode 偏说方案一是超时的,就好像它是通过你的代码来判断是不是超时而不是通过运行结果。
真是一道烂题目。