C++ unordered_set Solution 12ms


  • 0
    I

    Unordered_set is basically as hashset for C++.

    #include <unordered_set>
    class Solution {
    public:
        bool hasCycle(ListNode *head) {
            std::unordered_set<ListNode*> nodesSeen;
            while (head) 
            {
                if (nodesSeen.find(head)!=nodesSeen.end())  // If found then there is a cycle
                    return true;
                else
                    nodesSeen.insert(head); // If not found, insert to unordered_set
                if(head) head = head->next; // Move to next
            }
            return false;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.