My Java hashmap solution using O(n) time complexity.


  • 1
    L
    /**
     * Definition for singly-linked list.
     * class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) {
     *         val = x;
     *         next = null;
     *     }
     * }
     */
    public class Solution {
        public ListNode detectCycle(ListNode head) {
    	if (head == null) return null;
    	HashMap<String, Integer> map = new HashMap<String, Integer>();
    	for (ListNode cur = head; cur != null; cur = cur.next) {
    	    if (!map.containsKey(cur.toString())) map.put(cur.toString(), 0);
    	    else return cur;
    	}
    	return null;          
        }
    }

Log in to reply
 

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