leetcode(40).160. Intersection of Two Linked Lists
来源:互联网 发布:孕妇装比较好的淘宝店 编辑:程序博客网 时间:2024/06/01 10:16
题意:
这个太好懂了。性能不算太好,也不算太差。
这方法挺6的,但确实没想到。
给出两个链表,返回它们交集的起点。
初步分析:
核心在于指针要同时到达相交结点。一种方法:hashset找相同
/** * 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) { HashSet<Integer> hs = new HashSet<>(); while(headA!=null) { hs.add(headA.val); headA = headA.next; } while(headB!=null) { if(!hs.add(headB.val)) return headB; headB = headB.next; } return null; }}
这个太好懂了。性能不算太好,也不算太差。
对于双指针的话,直观的想法就是,长的那一者先走一段距离(这段距离是两条链表长度的差值),那么现在两条链表的指针到null的距离就相等了。现在就可以直接同步查找了。
这个也好想,但也不是很好。
贴一段别人的代码:动态的来把两个指针放在距离各自尾端相同距离的位子上。怎么实现呢?我们从头开始走,假设有一者更短,那么它先走完,这时候把它放到另一条链表(长的)的头部继续走,当长的链表的原本的指针走到尾部的时候,它正好走到了我们期待的位置。再把另一个指针放到另一条链表(短链表)的开头。
所以:
public ListNode getIntersectionNode(ListNode headA, ListNode headB) { ListNode p1 = headA, p2 = headB; while (p1 != p2) { if (p1 == null) { p1 = headB; // switch to headB } else { p1 = p1.next; } if (p2 == null) { p2 = headA; // switch to headA } else { p2 = p2.next; } } return p1;}
这方法挺6的,但确实没想到。
0 0
- [LeetCode]160.Intersection of Two Linked Lists
- LeetCode 160. Intersection of Two Linked Lists
- 【LeetCode】160.Intersection of Two Linked Lists
- [leetcode] 160.Intersection of Two Linked Lists
- [LeetCode]160. Intersection of Two Linked Lists
- LeetCode--160. Intersection of Two Linked Lists
- LeetCode 160. Intersection of Two Linked Lists
- 【LeetCode】160. Intersection of Two Linked Lists
- Leetcode 160. Intersection of Two Linked Lists
- LeetCode *** 160. Intersection of Two Linked Lists
- LeetCode 160. Intersection of Two Linked Lists
- leetcode-160. Intersection of Two Linked Lists
- LeetCode-160.Intersection of Two Linked Lists
- LeetCode 160. Intersection of Two Linked Lists
- Leetcode 160. Intersection of Two Linked Lists
- LeetCode 160. Intersection of Two Linked Lists
- leetcode 160. Intersection of Two Linked Lists
- 160.[Leetcode]Intersection of Two Linked Lists
- std::sort引发的core
- Spinner下拉列表的学习心得
- 桥接模式(Bridge)
- Ubuntu14.04全分布式安装hadoop2.7.2(二)下载安装+ssh免密码登陆
- NS2 学习资料网站链接
- leetcode(40).160. Intersection of Two Linked Lists
- CVPR 2016-11-18
- [iOS]UINavigationController全屏pop之为控制器添加左滑push
- forward 和redirect的区别
- MVC在Android中的应用
- 彩笔笔记2016/11/23——创建用户与配置挂载新硬盘
- 。
- 验证歌德巴赫猜想
- rapidjson建立json