[PS] Leet | 141. 연결 리스트 순환

2025. 5. 3. 18:37·CS/PS

문제

Given head, the head of a linked list, determine if the linked list has a cycle in it.

There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter.

Return true if there is a cycle in the linked list. Otherwise, return false.

 

Solve it using O(1) (i.e. constant) memory.

예시

Example 1:
Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).

 

Example 2:
Input: head = [1,2], pos = 0
Output: true
Explanation: There is a cycle in the linked list, where the tail connects to the 0th node.

 

Example 3:
Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.

조건

  • The number of the nodes in the list is in the range [0, 104].
  • -105 <= Node.val <= 105
  • pos is -1 or a valid index in the linked-list.

답

공간 복잡도 O(1)으로 해결하기 위해서 Floyd’s Tortoise and Hare 알고리즘을 이용합니다.

 

서로 다른 속도로 리스트를 순회하는 두 객체를 생성하여 반복문을 진행하고,

 

두 객체가 같은 지점에서 만난다면 순환구조가 존재하는 것으로 볼 수 있습니다.

 

반대로 빠른 객체 쪽이 tail.next = null 인 지점에 도착해 순회가 종료되면 순환구조가 없다고 볼 수 있습니다.

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */

/**
 * @param {ListNode} head
 * @return {boolean}
 */
var hasCycle = function(head) {
    let nodeFast = head;
    let nodeSlow = head;
    
    while(nodeFast && nodeFast.next) {
        nodeFast = nodeFast.next.next;
        nodeSlow = nodeSlow.next;

        if (nodeFast === nodeSlow) return true;
    }

    return false;
};

시간 복잡도 : O(n)

공간 복잡도 : O(1)

728x90

'CS > PS' 카테고리의 다른 글

[PS] Leet | 143. 리스트 재배치  (0) 2025.05.12
[PS] Leet | 23. 정렬된 K개의 리스트 합치기  (0) 2025.05.09
[PS] Leet | 435. 겹치지 않는 구간들  (0) 2025.04.30
[PS] Leet | 57. 구간 삽입  (0) 2025.04.26
[PS] Leet | 128. 가장 긴 연속 수  (0) 2025.04.24
'CS/PS' 카테고리의 다른 글
  • [PS] Leet | 143. 리스트 재배치
  • [PS] Leet | 23. 정렬된 K개의 리스트 합치기
  • [PS] Leet | 435. 겹치지 않는 구간들
  • [PS] Leet | 57. 구간 삽입
Rayi
Rayi
  • Rayi
    아카이브
    Rayi
  • 전체
    오늘
    어제
    • 분류 전체보기 (262)
      • CS (40)
        • ML (3)
        • CV (2)
        • PS (34)
      • Reveiw (17)
        • Paper (17)
        • Github (0)
      • Pytorch (5)
      • Language (58)
        • Python (7)
        • JavaScript (32)
        • TypeScript (16)
        • C++ (3)
      • IDE (12)
      • Git (13)
      • Frontend (71)
        • React (8)
        • SolidJS (20)
        • CSS (12)
      • UI (3)
      • Backend (15)
        • DB (17)
        • Node.js (11)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    figma
    html
    frontend
    CSS
    PyTorch
    CV
    review
    nodejs
    GAN
    ts
    CS
    Git
    Express
    postgresql
    mongo
    ML
    ps
    SOLID
    API
    DB
    deploy
    Three
    backend
    PRISMA
    react
    js
    C++
    python
    vscode
    UI
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.5
Rayi
[PS] Leet | 141. 연결 리스트 순환
상단으로

티스토리툴바