朴素的解法,先遍历链表1,将每个节点哈希值存入set,然后从链表2中找寻存在于set中的节点
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
import java.util.HashSet;
public class Solution {
//存到set中,出现同则为公共
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
HashSet<Integer> findSet = new HashSet<>();
ListNode curHead1 = pHead1;
ListNode curHead2 = pHead2;
while(curHead1!=null){
int temp=curHead1.hashCode();
if(!findSet.contains(temp)){
findSet.add(temp);
}
curHead1=curHead1.next;
}
while(curHead2!=null){
if(findSet.contains(curHead2.hashCode())){
return curHead2;
}
curHead2=curHead2.next;
}
return null;
}
}
京公网安备 11010502036488号