标签:空间 node 长度 剑指offer find java tpi pid hashset
题目链接:
分析:
空间换时间,记录下list1的所有节点,遍历list2时判断是否在list1已存在。
/* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }*/ import java.util.HashSet; public class Solution { public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) { //记录下list1的所有节点 HashSet<ListNode> set = new HashSet<>(); ListNode cur = pHead1; while(cur != null){ set.add(cur); cur = cur.next; } cur = pHead2; while(cur != null){ if(set.contains(cur)){ return cur; } cur = cur.next; } return null; } }
方法二:
由于列表只能指向一个节点,所以一定有个共同尾部,那么可以先让长链表先走比短表多出来的长度,然后同时遍历,找到共同节点。
/* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }*/ public class Solution { public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) { //获取两个链表的长度 int len1 = getLength(pHead1); int len2 = getLength(pHead2); //让长链表先走相差的距离 if(len1 >= len2){ ListNode cur = pHead1; int dis = len1 - len2; while(dis>0){ pHead1=pHead1.next; dis--; } }else{ int dis = len2 - len1; while(dis>0){ pHead2=pHead2.next; dis--; } } //遍历到公共节点 while(pHead1!=pHead2){ pHead1 = pHead1.next; pHead2 = pHead2.next; } return pHead1; } public int getLength(ListNode cur){ int len =0; while(cur != null){ len++; cur = cur.next; } return len; } }
标签:空间 node 长度 剑指offer find java tpi pid hashset
原文地址:https://www.cnblogs.com/MoonBeautiful/p/13070104.html