精華區beta Marginalman 關於我們 聯絡資訊
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