Write a program to find the node at which the intersection of two singly linked lists begins.

For example, the following two linked lists:

A:          a1 → a2

c1 → c2 → c3

B: b1 → b2 → b3

begin to intersect at node c1.

Notes:

  • If the two linked lists have no intersection at all, return null.
  • The linked lists must retain their original structure after the function returns.
  • You may assume there are no cycles anywhere in the entire linked structure.
  • Your code should preferably run in O(n) time and use only O(1) memory.

题目标签:Linked List

  题目给了我们两个链表,让我们找到它们是否有交点,返回那个交点。

  试想一下,如果是两个长度相等的链表,那么我们只需要遍历链表,比较两个点 是否 相等 就可以了。

  所以,我们首先要得到两个链表的长度,如果不一样长,那么把长的链表先走,走到 和 另外一个链表一样长度的时候,开始比较两个点 是否 相等来找到交点;如果没有,那么最后就返回null。

  如果两个链表有交点的话,那么从交点前一个点开始,两个链表从这里开始,之后的长度一定是相等的。

Java Solution:

Runtime beats 41.31%

完成日期:06/09/2017

关键词:singly-linked list

关键点:让更长的链表先走完多余的部分

 /**
* 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 cursor1 = headA;
ListNode cursor2 = headB;
int len1 = getListLength(cursor1);
int len2 = getListLength(cursor2); if(len1 > len2)
{
for(int i=0; i<len1-len2;i++)
cursor1 = cursor1.next;
}
else if(len1 < len2)
{
for(int i=0; i<len2-len1;i++)
cursor2 = cursor2.next;
} while(cursor1 != null)
{
if(cursor1 == cursor2)
return cursor1; cursor1 = cursor1.next;
cursor2 = cursor2.next;
} return null;
} private int getListLength(ListNode head)
{
ListNode cursor = head;
int len = 0; while(cursor != null)
{
cursor = cursor.next;
len++;
} return len;
}
}

参考资料:N/A

LeetCode 题目列表 - LeetCode Questions List

题目来源:https://leetcode.com/

最新文章

  1. c# .net获取随机字符串!
  2. Storm 中什么是-acker,acker工作流程介绍
  3. arcgis python 更新顺序号
  4. dancing link模板
  5. easyui datagrid 部分参数整理
  6. DOM笔记(二):Node接口
  7. django 学习-1
  8. 【MINA】用mina做业务服之间的通信,实现业务负载均衡思路
  9. 查询grep结果的前后n行
  10. IntelliJ Idea取消Could not autowire. No beans of &#39;xxxx&#39; type found的错误提示
  11. NET基础课--配置文件2
  12. nodejs文件操作模块FS(File System)常用函数简明总结(转)
  13. Evensgn 的债务
  14. PyQt:自定义QLineEdit禁止选中复制粘贴
  15. Uni-app中Class绑定与Style绑定
  16. Linux中安装nodejs及插件
  17. 原型链、闭包四种作用、继承、命名空间、枚举类型(day13)
  18. zabbix实现对tomcat的监控
  19. linux 防火墙 ufw使用
  20. python实现切换代理ip

热门文章

  1. Probabilistic locking in SQLite
  2. 最优化方法系列:Adam+SGD—>AMSGrad
  3. WINVER WIN32 WINNT
  4. LeetCode15——3Sum
  5. 判断机型是否为iphoneX
  6. Iframe用法精析
  7. STL源码分析之第二级配置器
  8. 线性DP LIS浅谈
  9. 1007 Maximum Subsequence Sum (PAT(Advance))
  10. Centos6文本安装教程