Leetcode No.83 Remove Duplicates from Sorted List移除有序数组中的重复元素(c++实现)
1. 题目
1.1 英文题目
Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.
1.2 中文题目
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
1.3输入输出
输入 | 输出 |
---|---|
head = [1,1,2] | [1,2] |
head = [1,1,2,3,3] | [1,2,3] |
1.4 约束条件
- The number of nodes in the list is in the range [0, 300].
- -100 <= Node.val <= 100
- The list is guaranteed to be sorted in ascending order.
2. 分析
2.1 自己的算法
该算法逻辑不太清晰
代码如下:
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if (head == nullptr || head->next == nullptr) {
return head;
}
ListNode* ptr = head;
ListNode ansHead(0);
ListNode* ans = &ansHead;
while (ptr != nullptr) {
ListNode* nextNode = ptr->next;
if (nextNode != nullptr && nextNode->val == ptr->val) {
ptr->next = nextNode->next;
if (ptr->next == nullptr || ptr->next->val != ptr->val) {
ans->next = ptr;
ans = ans->next;
}
}
else {
ans->next = ptr;
ans = ans->next;
}
ptr = ptr->next;
}
return ansHead.next;
}
};
参考:https://leetcode.com/problems/merge-two-sorted-lists/discuss/9714/14-line-clean-C%2B%2B-Solution
2.2 大牛算法
该算法不仅代码简洁,而且还避免了内存泄漏的问题。
代码如下:
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
ListNode* cur = head;
while (cur != nullptr && cur->next != nullptr) {
if (cur->val == cur->next->val) {
ListNode* tmp = cur->next;
cur->next = cur->next->next;
delete tmp;//删除重复节点,从而避免内存泄漏问题
}
else {
cur = cur->next;
}
}
return head;
}
};
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】