My java solution using HashSet


  • 3
    S
    public class Solution {
        public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
            HashSet<ListNode> set = new HashSet<ListNode>();
            while(headA!=null||headB!=null){
                if(headA!=null) {
                    if(set.contains(headA)){
                        return headA;
                    } else {
                        set.add(headA);
                    }
                    headA=headA.next;
                }
           
                if(headB!=null) {
                    if(set.contains(headB)) {
                        return headB;
                    } else {
                        set.add(headB);
                    }
                    headB=headB.next;
                }
            }
            return null;
            
        }
    }

  • 0
    C

    also add this in the beginning to prevent unnecessary scans:

        if( headA == null || headB == null ) {
            return null;
        }

  • 0
    M

    But you used O(n) space right?


Log in to reply
 

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