剑指offer (为什么我用时28ms,别人2ms)?
剑指offer JZ22 链表中倒数最后k个结点
同样的代码,别人用时2ms,376KB;在我的电脑上28ms,5000KB;
其他的题目我的电脑也比别人慢,但也就几毫秒,这题太离谱了,有大佬给解释下原因吗?
下面是我的代码:
struct ListNode* FindKthToTail(struct ListNode* pHead, int k ) {
if(pHead == NULL || k == 0){
return NULL;
}
struct ListNode* ptr1 = pHead;
static int i = 0;
for(i ; i < k; i++){
if(ptr1->next != NULL && i != k-1){
ptr1 = ptr1->next;
} else {
break;
}
}
if(i < k-1){
return NULL;
} else {
while(ptr1->next != NULL){
ptr1 = ptr1->next;
pHead = pHead->next;
}
}
return pHead;
}
#剑指offer##C/C++#struct ListNode* FindKthToTail(struct ListNode* pHead, int k ) {
if(pHead == NULL || k == 0){
return NULL;
}
struct ListNode* ptr1 = pHead;
static int i = 0;
for(i ; i < k; i++){
if(ptr1->next != NULL && i != k-1){
ptr1 = ptr1->next;
} else {
break;
}
}
if(i < k-1){
return NULL;
} else {
while(ptr1->next != NULL){
ptr1 = ptr1->next;
pHead = pHead->next;
}
}
return pHead;
}