zoukankan      html  css  js  c++  java
  • 求两个单链表的交集,O(1) 的空间复杂度和 O(n) 的时间复杂度,且不能改变原先的链表

    把这个像复杂了,因为之前判断链表是否回文的经验,想从递归的延迟求值的特性来从两个链表的终点递归来确定交集的头结点,甚难。

    后来看了一位朋友的博客,明白了原来是只要找第一个相同的头结点就行了,那这个就简单了。

    代码如下:

    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        if (headA == nullptr || headB == nullptr){
            return nullptr;
        }
        
        auto length = [](ListNode*& node)
        {
            int len = 0;
            for (auto it = node; it != nullptr; it = it->next){
                ++len;
            }
            return len;
        };
        
        const auto      lenA = length(headA);
        const auto      lenB = length(headB);
        
        auto moveForward = [](ListNode*& node, size_t&& count)
        {
            while (count != 0) {
                node = node->next;
                --count;
            }
            return node;
        };
        
        ListNode* it1  = nullptr;
        ListNode* it2  = nullptr;
        
        if (lenA < lenB){
            it1 = headA;
            it2 = moveForward(headB, lenB - lenA);
        }
        else{
            it1 = moveForward(headA, lenA - lenB);
            it2 = headB;
        }
        
        while (it2 != nullptr){
            if (it1->val == it2->val){
                return it1;
            }
            
            it1 = it1->next;
            it2 = it2->next;
        }
        return nullptr;
    }
  • 相关阅读:
    图解设计模式-Visitor模式
    图解设计模式-Decorator模式
    图解设计模式-Strategy模式
    图解设计模式-Bridge模式
    HashMap源码
    LinkedList源码
    Vector源码
    ArrayList源码
    图解设计模式-Abstract Factory模式
    图解设计模式-Builder模式
  • 原文地址:https://www.cnblogs.com/wuOverflow/p/4719765.html
Copyright © 2011-2022 走看看