zoukankan      html  css  js  c++  java
  • [LeetCode] Intersection of Two Linked Lists

    Question:

    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.

    1、题型分类:

    2、思路:

    3、时间复杂度:O(n)

    4、代码:

    空间复杂度O(n)

    public class Solution {
        public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
            if(headA==null || headB==null) return null;
            Set<ListNode> set=new HashSet<ListNode>();
            while(headA!=null)
            {
                if(set.contains(headA)) return headA;
                else set.add(headA);
                headA=headA.next;
            }
            while(headB!=null)
            {
                if(set.contains(headB)) return headB;
                else set.add(headB);
                headB=headB.next;
            }
            return null;
        }
    }

    5、优化:

    先计算两个链表的长度,然后分别从相同长度的节点开始遍历,遇到相同的元素返回。

    public class Solution {
        
        public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
            int lenA = getLen(headA);
            int lenB = getLen(headB);
            
            ListNode shortHead = headA;
            ListNode longHead = headB;
            if (lenA > lenB) {
                shortHead = headB;
                longHead = headA;
            }
            
            int i = 0;
            while (i < Math.abs(lenB - lenA)) {
                i++;
                longHead = longHead.next;
            }
            
            while (shortHead != longHead) {
                shortHead = shortHead.next;
                longHead = longHead.next;
                
                
                if (shortHead == null) {
                    return null;
                }
            }
            return shortHead;
        }
        
        private int getLen(ListNode head) {
            int len = 0;
            while (head != null) {
                len++;
                head = head.next;
            }
            return len;
        }
    }

    6、扩展:

  • 相关阅读:
    7牛管理凭证生成错误
    安卓截屏如何实现将摄像头显示画面截下来
    realm怎样支持hashmap
    Cordova Android项目如何做代码混淆
    cnmp安装失败,报错npm ERR! enoent ENOENT: no such file or directory,
    iOS中关于字符 “&”的作用?
    float 保留两位小数
    关于iOS声音识别的框架
    iOS崩溃日志
    QT分析之WebKit
  • 原文地址:https://www.cnblogs.com/maydow/p/4644150.html
Copyright © 2011-2022 走看看