【LeetCode】[160] 相交链表-哈希表

我的代码-哈希表屡用不爽

import java.util.HashMap;

/*
 * @lc app=leetcode.cn id=160 lang=java
 *
 * [160] 相交链表
 */
//  Definition for singly-linked list.
class ListNode {
    int val;
    ListNode next;
    ListNode(int x) {
        val = x;
        next = null;
    }
}
class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if (headA == null || headB == null) return null;
        if (headA == headB) return headA;
    
        HashMap<ListNode, Integer> hashMap = new HashMap<ListNode, Integer>();
        hashMap.put(headA, headA.val);
        hashMap.put(headB, headB.val);
        ListNode nextA = headA.next;
        ListNode nextB = headB.next;
        while (nextA != null && nextB != null) {
            if (!hashMap.containsKey(nextA)) {
                hashMap.put(nextA, nextA.val);
            } else {
                return nextA;
            }
            if (!hashMap.containsKey(nextB)) {
                hashMap.put(nextB, nextB.val);
            } else {
                return nextB;
            }

            nextA = nextA.next;
            nextB = nextB.next;
        }
        while (nextA != null) {
            if (!hashMap.containsKey(nextA)) {
                hashMap.put(nextA, nextA.val);
            } else {
                return nextA;
            }
            nextA = nextA.next;
        }
        while (nextB != null) {
            if (!hashMap.containsKey(nextB)) {
                hashMap.put(nextB, nextB.val);
            } else {
                return nextB;
            }
            nextB = nextB.next;
        }
        return null;
    }
}


大佬的代码-巧妙解法

public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        /**
        定义两个指针, 第一轮让两个到达末尾的节点指向另一个链表的头部, 最后如果相遇则为交点(在第一轮移动中恰好抹除了长度差)
        两个指针等于移动了相同的距离, 有交点就返回, 无交点就是各走了两条指针的长度
        **/
        if(headA == null || headB == null) return null;
        ListNode pA = headA, pB = headB;
        // 在这里第一轮体现在pA和pB第一次到达尾部会移向另一链表的表头, 而第二轮体现在如果pA或pB相交就返回交点, 不相交最后就是null==null
        while(pA != pB) {
            pA = pA == null ? headB : pA.next;
            pB = pB == null ? headA : pB.next;
        }
        return pA;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值