相交链表–java–哈希表
思路:
这道题,很容易想到的就是双循环暴力来做,也是一道很少有的LeetCode暴力不超时的题
第二种思路是使用哈希表来做,先将A遍历,放入哈希表中,然后再遍历B,如果B中的元素
在哈希表中存在,则返回该元素,否则返回null
代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
// 方法一:暴力法
// public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
// ListNode a = headA;
// ListNode b = headB;
// while( a != null ){
// b = headB;
// while( b != null ){
// if( a == b ){
// return a;
// }
// b = b.next;
// }
// a = a.next;
// }
// return null;
// }
// 方法二:哈希表
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode a = headA;
ListNode b = headB;
Set<ListNode> set = new HashSet<>();
// 遍历A,将其放入哈希表中
while( a != null ){
set.add(a);
a = a.next;
}
// 查看B中元素在哈希表中是否存在,如果存在,返回该元素
while( b != null ){
if( set.contains(b) ){
return b;
}
b = b.next;
}
return null;
}
}