diff --git a/算法/B类:数据结构算法/4.2 链表与双指针.md b/算法/B类:数据结构算法/4.2 链表与双指针.md index 9accb590..5044415e 100644 --- a/算法/B类:数据结构算法/4.2 链表与双指针.md +++ b/算法/B类:数据结构算法/4.2 链表与双指针.md @@ -44,4 +44,56 @@ } return first; } +``` + +## 2 两个链表的第一个公共节点 + +### 问题描述 + +输入两个链表,找出它们的第一个公共节点。这两个链表不相交,返回 null。 +![](image/2021-03-26-21-18-15.png) + +要求: +* 如果两个链表没有交点,返回 null. +* 在返回结果后,两个链表仍须保持原有的结构。 +* 可假定整个链表结构中没有循环。 +* 程序尽量满足 O(n) 时间复杂度,且仅用 O(1) 内存。 +[链接](https://leetcode-cn.com/problems/liang-ge-lian-biao-de-di-yi-ge-gong-gong-jie-dian-lcof) +### 问题分析 + +* 问题类别:双指针 + +### 策略选择 + +* 数据结构:线性数据结构 +* 算法思想:双指针 + +### 算法设计 +* 我们使用两个指针 node1,node2 分别指向两个链表 headA,headB 的头结点,然后同时分别逐结点遍历, +* 当 node1 到达链表 headA 的末尾时,重新定位到链表 headB 的头结点; +* 当 node2 到达链表 headB 的末尾时,重新定位到链表 headA 的头结点。 + +![](image/2021-03-26-21-22-32.png) + +### 算法分析 + +- 时间复杂度:O(M+N)O(M+N)。 +- 空间复杂度:O(1)O(1)。 + +### 算法实现 + +```C++ +class Solution { +public: + ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { + ListNode *node1 = headA; + ListNode *node2 = headB; + + while (node1 != node2) { + node1 = node1 != NULL ? node1->next : headB; + node2 = node2 != NULL ? node2->next : headA; + } + return node1; + } +}; ``` \ No newline at end of file diff --git a/算法/B类:数据结构算法/image/2021-03-26-21-18-15.png b/算法/B类:数据结构算法/image/2021-03-26-21-18-15.png new file mode 100644 index 00000000..55a469dc Binary files /dev/null and b/算法/B类:数据结构算法/image/2021-03-26-21-18-15.png differ diff --git a/算法/B类:数据结构算法/image/2021-03-26-21-22-32.png b/算法/B类:数据结构算法/image/2021-03-26-21-22-32.png new file mode 100644 index 00000000..52c25bdb Binary files /dev/null and b/算法/B类:数据结构算法/image/2021-03-26-21-22-32.png differ diff --git a/算法/C类:问题类型算法/1.1 重复问题.md b/算法/C类:问题类型算法/1.1 重复问题.md index e7cd8c21..3925974f 100644 --- a/算法/C类:问题类型算法/1.1 重复问题.md +++ b/算法/C类:问题类型算法/1.1 重复问题.md @@ -140,7 +140,21 @@ 3. 返回值: 返回 x 即可; ### 算法分析 -* 时间复杂度 O(N)O(N) : NN 为数组 nums 长度。 -* 空间复杂度 O(1)O(1) : votes 变量使用常数大小的额外空间。 +* 时间复杂度 O(N) : N 为数组 nums 长度。 +* 空间复杂度 O(1): votes 变量使用常数大小的额外空间。 -### 算法实现 \ No newline at end of file +### 算法实现 + +``` +class Solution { +public: + int majorityElement(vector& nums) { + int x = 0, votes = 0; + for(int num : nums){ + if(votes == 0) x = num; + votes += num == x ? 1 : -1; + } + return x; + } +}; +``` \ No newline at end of file