zoukankan      html  css  js  c++  java
  • 160. Intersection of Two Linked Lists

    题目:

    复制代码
    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.
    复制代码

    链接:  http://leetcode.com/problems/intersection-of-two-linked-lists/

    2/19/2017, Java

    一开始的思路是,借用判断cycled linked list来。先从nodeA出发遍历,把最后一个node的next设为nodeB的head,这样第二次遍历时候通过slow, fast来找进入圈里的第一个node。

    看起来很巧妙,但是是错误的,因为无法确定当fast, slow相遇时,是否是在进入圈里的第一个node,其实,可能为任一node。

    正确解法,借鉴别人:

    判断2个list的长度差,从距末尾相同长度开始(此时至少一个list是在head),一个个比较。

    注意第一步之后要将a, b重新设到合理的位置,尤其是diff == 0时

     1 public class Solution {
     2     public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
     3         if (headA == null || headB == null) return null;
     4         int diff = 0;
     5         ListNode a = new ListNode(0);
     6         ListNode b = new ListNode(0);
     7         a = headA;
     8         b = headB;
     9         
    10         while(a != null && b != null) {
    11             a = a.next;
    12             b = b.next;
    13         }
    14         while (a != null) {
    15             diff++;
    16             a = a.next;
    17         }
    18         while (b != null) {
    19             diff--;
    20             b = b.next;
    21         }
    22         if (diff > 0) {
    23             a = headA;
    24             while (diff > 0) {
    25                 a = a.next;
    26                 diff--;
    27             }
    28             b = headB;
    29         } else if (diff < 0) {
    30             b = headB;
    31             while (diff < 0) {
    32                 b = b.next;
    33                 diff++;
    34             }
    35             a = headA;
    36         } else {
    37             a = headA;
    38             b = headB;
    39         }
    40         
    41         while (a != null && b != null) {
    42             if (a == b) return a;
    43             a = a.next;
    44             b = b.next;
    45         }
    46         return null;
    47     }
    48 }
  • 相关阅读:
    Hbase 性能改进
    HBase总结(十一)hbase Java API 介绍及使用示例
    Java中如何遍历Map对象的4种方法
    Jsp分页实例---假分页
    Jsp分页实例---真分页
    Java正则表达式
    平均时间复杂度为O(nlogn)的排序算法
    常见排序算法--简单排序
    [kuangbin带你飞]专题一 简单搜索
    [kuangbin带你飞]专题一 简单搜索
  • 原文地址:https://www.cnblogs.com/panini/p/6418745.html
Copyright © 2011-2022 走看看