File tree Expand file tree Collapse file tree 1 file changed +67
-0
lines changed Expand file tree Collapse file tree 1 file changed +67
-0
lines changed Original file line number Diff line number Diff line change 1+ import java .util .ArrayList ;
2+ import java .util .HashMap ;
3+ import java .util .HashSet ;
4+ import java .util .List ;
5+ import java .util .Map ;
6+ import java .util .Set ;
7+
8+ public class Solution {
9+ public boolean hasCycle (ListNode head ) {
10+ Set <ListNode > nSet = new HashSet <>();
11+
12+ while (head != null ) {
13+ if (nSet .contains (head )) {
14+ return true ;
15+ }
16+
17+ nSet .add (head );
18+ head = head .next ;
19+ }
20+
21+ return false ;
22+ }
23+ }
24+
25+ /**
26+ * Definition for singly-linked list.
27+ * class ListNode {
28+ * int val;
29+ * ListNode next;
30+ * ListNode(int x) {
31+ * val = x;
32+ * next = null;
33+ * }
34+ * }
35+ */
36+ // NOTE: 같은 val의 다른 Node의 경우를 고려하지 못했다
37+ class WrongSolution {
38+ public boolean hasCycle (ListNode head ) {
39+ Map <Integer , List <Integer >> vMap = new HashMap <>(); // NOTE: val, pos
40+
41+ if (head == null ) {
42+ return false ;
43+ }
44+
45+ ListNode cur = head ;
46+ boolean isCyclick = false ;
47+ int pos = -1 ;
48+ while (cur != null ) {
49+
50+ if (vMap .containsKey (cur .val )) {
51+ isCyclick = true ;
52+ break ;
53+ }
54+
55+ List <Integer > posList = new ArrayList <>();
56+ posList .add (pos ++);
57+ vMap .put (cur .val , posList );
58+ cur = head .next ;
59+ }
60+
61+ if (isCyclick ) {
62+ return true ;
63+ } else {
64+ return false ;
65+ }
66+ }
67+ }
You can’t perform that action at this time.
0 commit comments