일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
- UI
- CV
- Express
- SOLID
- Git
- GAN
- html
- ML
- review
- js
- frontend
- DM
- vscode
- react
- ts
- PyTorch
- mongo
- CSS
- PRISMA
- ps
- figma
- Linux
- C++
- python
- sqlite
- Three
- postgresql
- nodejs
- DB
- API
- Today
- Total
아카이브
[PS] Leet | 141. 연결 리스트 순환 본문
문제
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)
'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 |