KimMinJun
Coding Note
KimMinJun
전체 방문자
오늘
어제
  • 분류 전체보기 (486)
    • ALGORITHM (11)
      • 정렬 (6)
      • 최단경로 (1)
      • 자료구조 (1)
      • 슬라이딩 윈도우 (1)
      • etc (2)
    • Git (5)
    • Web (24)
      • Vanilla JS (13)
      • TS (2)
      • React (7)
      • ETC (1)
    • React 공식문서 (번역, 공부) (11)
      • Quick Start (2)
      • Installation (0)
      • Describing the UI (9)
      • Adding Interactivity (0)
      • Managing State (0)
      • Escape Hatches (0)
    • Next.js 공식문서 (번역, 공부) (3)
      • Getting Started (2)
      • Building Your Application (1)
    • PS (431)
      • 백준 (187)
      • Programmers (104)
      • CodeUp (21)
      • STL (3)
      • 제코베 JS 100제 (50)
      • SWEA (0)
      • LeetCode (65)
    • IT (1)

블로그 메뉴

  • 홈
  • 태그
  • 방명록
  • 관리

공지사항

인기 글

태그

  • codeup
  • 다이나믹 프로그래밍
  • programmers
  • Level 1
  • Level 2
  • Level 0
  • C++
  • 제코베 JS 100제
  • LeetCode
  • tree
  • 수학
  • 문자열
  • recursion
  • 정렬
  • js
  • string
  • 그래프
  • 백준
  • Level1
  • C

최근 댓글

최근 글

hELLO · Designed By 정상우.
KimMinJun

Coding Note

PS/LeetCode

LeetCode / Linked List / 142번 / Linked List Cycle II / JS

2023. 4. 1. 00:47

< 문제 바로가기 >

 

Linked List Cycle II - LeetCode

Can you solve this real interview question? Linked List Cycle II - Given the head of a linked list, return the node where the cycle begins. If there is no cycle, return null. There is a cycle in a linked list if there is some node in the list that can be r

leetcode.com

 

< 문제 간단설명 >

순환을 할 수도 있고, 순환하지 않을 수도 있는 Linked List가 주어진다.

만약 어딘가의 위치에서 순환이 이루어지고 있는 Linked List 라면, 순환이 이루어지고 있는 cycle 에서의 첫번째 노드를 반환해주면 되는 문제이다.

만약 순환이 없는 Linked List 라면 null을 반환해주면 된다.

 

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

/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var detectCycle = function(head) {
    let listNodeSet = new Set();

    while(head) {
        if(listNodeSet.has(head)) {
            return head;
        }
        listNodeSet.add(head);
        head = head.next;
    }

    return null;
};

모든 Linked List의 노드를 순회하면서 Set에 노드 자체를 넣어준다.

만약 cycle이 생기는 구간에 진입을 하면, cycle의 맨 마지막의 다음은 cycle의 맨 처음 노드일 것이다.

하지만 cycle의 맨 처음 노드는 cycle을 돌기전에 이미 한번 Set에 들어가있을것이다.

따라서 이미 Set에 있는 노드라면 그 노드를 반환을 해주면 된다.

저작자표시

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

LeetCode / Greedy / 409번 / Longest Palindrome / JS  (0) 2023.04.01
LeetCode / Greedy / 121번 / Best Time to Buy and Sell Stock / JS  (0) 2023.04.01
LeetCode / Linked List / 876번 / Middle of Linked List / JS  (0) 2023.04.01
LeetCode / Linked List / 206번 / Reverse Linked List / JS  (0) 2023.03.29
    'PS/LeetCode' 카테고리의 다른 글
    • LeetCode / Greedy / 409번 / Longest Palindrome / JS
    • LeetCode / Greedy / 121번 / Best Time to Buy and Sell Stock / JS
    • LeetCode / Linked List / 876번 / Middle of Linked List / JS
    • LeetCode / Linked List / 206번 / Reverse Linked List / JS
    KimMinJun
    KimMinJun

    티스토리툴바