File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change
1
+ //Definition for singly-linked list.
2
+ class ListNode {
3
+ int val ;
4
+ ListNode next ;
5
+ ListNode (int x ) {
6
+ val = x ;
7
+ next = null ;
8
+ }
9
+ }
10
+
11
+ class Solution {
12
+ public boolean hasCycle (ListNode head ) {
13
+ // ํ์ด 1: Set์ ๊ฐ์ฒด๋ฅผ ์ง์ด ๋ฃ๊ณ , ์ฌ์ด์ฆ๊ฐ ์๋์ด๋๋ฉด ์ฌ์ดํด์ด ์๋ค๊ณ ํ๋จํ ์ ์๋ค
14
+ // TC: O(N)
15
+ // SC: O(N)
16
+ // Set<ListNode> set = new HashSet<>();
17
+ //
18
+ // while(head != null) {
19
+ // var before = set.size();
20
+ // set.add(head);
21
+ // var after = set.size();
22
+ // if (before == after) {
23
+ // return true;
24
+ // }
25
+ // head = head.next;
26
+ // }
27
+ //
28
+ // return false;
29
+
30
+ // ํ์ด 2: ๋๊ฐ์ ํฌ์ธํฐ๋ฅผ ์ฌ์ฉํด ์ฒซ๋ฒ์งธ ํฌ์ธํฐ๋ ํ๋์ฉ, ๋๋ฒ์งธ ํฌ์ธํฐ๋ ๋๊ฐ์ฉ ์ํํ๋ค ๊ฒน์น๋ ๋ถ๋ถ์ด ์๊ธฐ๋ฉด ์ํ์ด๋ผ๊ณ ํ๋จํ ์ ์๋ค
31
+ // TC: O(N)
32
+ // SC: O(1)
33
+ var slow = head ;
34
+ var fast = head ;
35
+ while (fast != null && fast .next != null ) {
36
+ slow = slow .next ;
37
+ fast = fast .next .next ;
38
+
39
+ if (slow == fast ) {
40
+ return true ;
41
+ }
42
+ }
43
+
44
+ return false ;
45
+ }
46
+ }
You canโt perform that action at this time.
0 commit comments