141. Linked List Cycle

2021. 5. 3. 10:19·Algorithm
 

Linked List Cycle - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

1. Object id값과 집합을 이용한 풀이

class Solution:
    def hasCycle(self, head: ListNode) -> bool:
        id_set = set()
        cur = head
        while cur:
            if id(cur) not in id_set:
                id_set.add(id(cur))
            else:
                return True
            cur = cur.next
        return False

객체 id값은 고유하기 때문에 집합에 넣고 이미 현재 객체 id값이 집합에 있다면 사이클이 있음으로 판단한다.

 

2. Floyd의 순환 알고리즘

class Solution:
    def hasCycle(self, head: ListNode) -> bool:
        slow = fast = head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
            if slow == fast:
                return True
        return False

시간 복잡도나 공간 복잡도가 별 차이 나진 않지만 이렇게도 풀 순 있다.

'Algorithm' 카테고리의 다른 글

234. Palindrome Linked List  (0) 2021.05.04
226. Invert Binary Tree  (1) 2021.05.03
53. Maximum Subarray  (0) 2021.05.02
101. Symmetric Tree  (0) 2021.05.02
155. Min Stack  (0) 2021.04.30
'Algorithm' 카테고리의 다른 글
  • 234. Palindrome Linked List
  • 226. Invert Binary Tree
  • 53. Maximum Subarray
  • 101. Symmetric Tree
Doljae
Doljae
  • Doljae
    Zero to Hero
    Doljae
  • 전체
    오늘
    어제
    • 분류 전체보기 (350)
      • Programming (54)
      • Algorithm (161)
      • Review (103)
      • Career (8)
      • Diary (18)
      • Shorts (4)
      • Temp (2)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
    • 글 쓰기
    • 관리
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    2021
    db
    프로그래머스
    database
    PYTHON
    나는 리뷰어다
    컨퍼런스
    sql튜닝
    회고
    인프콘
    jpa
    코딩테스트
    코딩
    java
    나는리뷰어다
    line
    공채
    ChatGPT
    한빛미디어
    2022
    BOJ
    sql
    AI
    백준
    개발자
    라인
    leetcode
    면접
    mysql
    2023
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.4
Doljae
141. Linked List Cycle
상단으로

티스토리툴바