lurenaa的博客

🐶双指针

相当于将两个链表连在一起,一条是A + B, 一条是B + A,走过同样的长度。

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode* a = headA, *b = headB;
while(a != b) {
a = a == nullptr ? headB : a->next;
b = b == nullptr ? headA : b->next;
}
return a;
}
};

🚌set实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if(!head)
return nullptr;
set<ListNode*> st;
st.insert(head);
while(head) {
head = head->next;
if(!head)
return nullptr;
if(st.count(head)) {
return head;
} else {
st.insert(head);
}
}
return nullptr;
}
};

Accepted

16/16 cases passed (36 ms)

Your runtime beats 6.15 % of cpp submissions

Your memory usage beats 5.56 % of cpp submissions (12.1 MB)