Skip to content

leet code algorithm

문제 풀이의 핵심은 포인터를 두 개를 쓰는 것.

하나는 느리게 움직이고, 하나는 빠르게 움직이는 포인터를 둬서

빠르게 움직이는 포인터가 느리게 움직이는 포인터를 만날 수 있으면 루프가 있는 것입니다.

https://leetcode.com/explore/learn/card/linked-list/214/two-pointer-technique/1212/

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    bool hasCycle(ListNode *head) {
        if(head == nullptr)
        {
            return false;
        }
        if(head->next == nullptr)
        {
            return false;
        }
        int cnt=2;
        ListNode* ptr1= head->next;
        ListNode* ptr2= ptr1;
        while(ptr1!=nullptr)
        {
            if(ptr1->next == nullptr)
                return false;
            ptr2 = ptr1->next;
            for(int i=0; i<4000; i++)
            {
                if(ptr1==ptr2)
                {
                    return true;
                }
                if(ptr2->next==nullptr)
                {
                    return false;
                }
                ptr2 = ptr2->next;
            }
            ptr1=ptr1->next;
        }

        return false;
    }
};

update(240ms => 8ms)

위의 코드에서는 i가 4000번까지 무조건 돌아야 하는데,

여기에서는 빠른 포인터가 느린 포인터를 따라 잡습니다.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    bool hasCycle(ListNode *head) {
        if(head == nullptr)
            return false;
        if(head->next == nullptr)
            return false;
        if(head->next->next == nullptr)
            return false;
        ListNode *slow=head;
        ListNode *fast=head->next;
        while(1)
        {
            if(fast==nullptr||fast->next==nullptr||fast->next==nullptr)
                return false;
            if(slow==fast) return true;
            slow = slow->next;
            fast = fast->next->next;
        }
        return false;
    }
};