[Leetcode] Remove Duplicates from Sorted List II
来源:互联网 发布:mac子弹头口红价格 编辑:程序博客网 时间:2024/06/08 15:12
描述
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5
, return 1->2->5
.
Given 1->1->1->2->
3, return 2->3
.
保留链表中只出现一次的元素,将其他元素删除。
分析
这道题是 Remove Duplicates from Sorted List 的改进版,主要的区别在于前一题对出现多次的元素会保留,这道题不会。
我们可以采用减而治之的思想,对于 deleteDuplicates(head)
这个问题,如果前两个元素的值不同,那么问题就变成了 deleteDuplicates(head->next)
;如果前两个元素相同,那么找到第一个不同值的元素p,问题变成了 deleteDuplicates(p)
。对于平凡的情况,是链表为空或者只有一个元素,直接返回。
代码
class Solution {public: ListNode* deleteDuplicates(ListNode* head) { if (!head || !head->next) return head; if (head->val != head->next->val) { head->next = deleteDuplicates(head->next); return head; } while (head->next && head->next->val == head->val) head = head->next; return deleteDuplicates(head->next); }};
相关问题
Remove Duplicates from Sorted List
0 0
- LeetCode: Remove Duplicates from Sorted List II
- [Leetcode] Remove Duplicates from Sorted List II
- LeetCode: Remove Duplicates from Sorted List II
- [Leetcode] Remove Duplicates from Sorted List II
- [leetcode] Remove Duplicates from Sorted List II
- [LeetCode] Remove Duplicates from Sorted List II
- [leetcode] Remove Duplicates from Sorted List II
- [LeetCode]Remove Duplicates from Sorted List II
- [leetcode]Remove Duplicates from Sorted List II
- LeetCode-Remove Duplicates from Sorted List II
- [leetcode] Remove Duplicates from Sorted List II
- LeetCode - Remove Duplicates from Sorted List II
- LeetCode | Remove Duplicates from Sorted List II
- LeetCode:Remove Duplicates from Sorted List II
- 【leetcode】Remove Duplicates from Sorted List II
- Leetcode: Remove Duplicates from Sorted List II
- leetcode Remove Duplicates from Sorted List II
- [LeetCode] Remove Duplicates from Sorted List II
- import cv2 报错 Segmentation fault (core dumped)
- 配置Log4j
- 微信小程序—下拉刷新上拉加载
- 获取组件当中某个Drawable所在的坐标范围
- POJ - 1185 炮兵阵地
- [Leetcode] Remove Duplicates from Sorted List II
- LeetCode-476. Number Complement-思路详解-C++
- 共享动画的实现(AndroidL及以上)
- 设计模式之外观模式
- [BZOJ1414][ZJOI2009]对称的正方形(manacher+单调栈+二分)
- Java多态
- profile=epp.package.java, phase=org.eclipse.equinox.internal.p2.engine.phases.Collect, operand=, act
- 常用的字符串函数
- 设计模式【2】-对象行为型-状态模式