Java 23ms Solution Using HashMap


  • 0
    B
        public boolean hasCycle(ListNode head) {
            if (head==null) return false;
            ListNode currentNode = head;
            ListNode nextNode = currentNode.next;
            Map<Integer, ArrayList> map = new HashMap<Integer, ArrayList>();
            while(nextNode!=null){
                if(!map.containsKey(currentNode.val)){
                    ArrayList<ListNode> arr = new ArrayList<ListNode>();
                    arr.add(currentNode);
                    map.put(currentNode.val, arr);
                }
                else map.get(currentNode.val).add(currentNode);
                if(nextNode.next!=null&&map.containsKey(nextNode.next.val)){
                    for(int i = 0; i<map.get(nextNode.next.val).size();i++){
                        if(nextNode.next.equals(map.get(nextNode.next.val).get(i))){
                            return true;
                        }
                    }
                }
                currentNode = nextNode;
                nextNode = currentNode.next;
            }
            return false;
            
            
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.