作者SuiseiLeda (彗星雷達)
看板Marginalman
標題Re: [LeetCode] 刷到面試 Grind169 C++
時間Sun Mar 19 16:19:14 2023
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
推 DDFox: 大師 瘋狂刷題 03/19 16:19
→ SuiseiLeda: 不然我要失業了 03/19 16:23