3.2刷题记录 Linked List Cycle II(142)

加强版的快慢指针题,需要得出在哪里环的位置,就需要一个从头指针,一个slow,相碰的地方为环所在地,这是一个数学题。
这是快慢指针的方法
class Solution { public: ListNode *detectCycle(ListNode *head) { ListNode *slow = head, *fast = head; while (fast != nullptr) { slow = slow->next; if (fast->next == nullptr) { return nullptr; } fast = fast->next->next; if (fast == slow) { ListNode *ptr = head; while (ptr != slow) { ptr = ptr->next; slow = slow->next; } return ptr; } } return nullptr; } };
但是使用哈希表可以更简单的完成的。
class Solution { public: ListNode *detectCycle(ListNode *head) { unordered_set<ListNode*>hash; if(head==NULL||head->next==NULL) { return NULL; } while(head->next!=NULL) { if(!hash.count(head)) { hash.insert(head); head=head->next; } else { return head; break; } } return NULL; } };
但是运行时间真的很长就是了。最好还是快慢指针。

浙公网安备 33010602011771号