Why this c++ code gets TLE?


  • 0
    K
    #include <bits/stdc++.h>
    using namespace std;
    
    class Solution {
    public:
      ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        if (!headA || !headB) {
          return 0;
        }
        ListNode *t;
        int a=1, b=1;
        t=headA; while (t->next) { t=t->next, a++; } t->next=headB;
        t=headB; while (t->next) { t=t->next, b++; } t->next=headA;
        for (int i=0; i<a+b; i++) {
          if (headA->val==headB->val) {
            return headA;
          }
          headA=headA->next;
          headB=headB->next;
        }
        return 0;
      }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.