Re: [LeetCode] 刷到面試 Grind169 C++
141. Linked List Cycle easy題
兩種解法 哈希表跟雙指針
有趣
哈希
class Solution {
public:
bool hasCycle(ListNode *head) {
unordered_set<ListNode*> visited;
while(head){
if(visited.count(head)) return true;
visited.insert(head);
head=head->next;
}
return false;
}
};
雙指針
class Solution {
public:
bool hasCycle(ListNode *head) {
auto fast=head;
auto slow=head;
while(fast){
if(!fast->next) return false;
fast=fast->next->next;
slow=slow->next;
if(slow==fast) return true;
}
return false;
}
};
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 223.137.157.124 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1679213956.A.20A.html
推
03/19 16:19,
2年前
, 1F
03/19 16:19, 1F
→
03/19 16:23,
2年前
, 2F
03/19 16:23, 2F
討論串 (同標題文章)
完整討論串 (本文為第 13 之 14 篇):