mirror of
https://github.com/Estom/notes.git
synced 2026-04-13 18:00:27 +08:00
链表与双指针
This commit is contained in:
@@ -44,4 +44,56 @@
|
||||
}
|
||||
return first;
|
||||
}
|
||||
```
|
||||
|
||||
## 2 两个链表的第一个公共节点
|
||||
|
||||
### 问题描述
|
||||
|
||||
输入两个链表,找出它们的第一个公共节点。这两个链表不相交,返回 null。
|
||||

|
||||
|
||||
要求:
|
||||
* 如果两个链表没有交点,返回 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 的头结点。
|
||||
|
||||

|
||||
|
||||
### 算法分析
|
||||
|
||||
- 时间复杂度: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;
|
||||
}
|
||||
};
|
||||
```
|
||||
BIN
算法/B类:数据结构算法/image/2021-03-26-21-18-15.png
Normal file
BIN
算法/B类:数据结构算法/image/2021-03-26-21-18-15.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 15 KiB |
BIN
算法/B类:数据结构算法/image/2021-03-26-21-22-32.png
Normal file
BIN
算法/B类:数据结构算法/image/2021-03-26-21-22-32.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 73 KiB |
@@ -140,7 +140,21 @@
|
||||
3. 返回值: 返回 x 即可;
|
||||
### 算法分析
|
||||
|
||||
* 时间复杂度 O(N)O(N) : NN 为数组 nums 长度。
|
||||
* 空间复杂度 O(1)O(1) : votes 变量使用常数大小的额外空间。
|
||||
* 时间复杂度 O(N) : N 为数组 nums 长度。
|
||||
* 空间复杂度 O(1): votes 变量使用常数大小的额外空间。
|
||||
|
||||
### 算法实现
|
||||
### 算法实现
|
||||
|
||||
```
|
||||
class Solution {
|
||||
public:
|
||||
int majorityElement(vector<int>& nums) {
|
||||
int x = 0, votes = 0;
|
||||
for(int num : nums){
|
||||
if(votes == 0) x = num;
|
||||
votes += num == x ? 1 : -1;
|
||||
}
|
||||
return x;
|
||||
}
|
||||
};
|
||||
```
|
||||
Reference in New Issue
Block a user