LeetCode题解 week15
来源:互联网 发布:java第十版基础篇答案 编辑:程序博客网 时间:2024/05/16 02:14
82. Remove Duplicates from Sorted List II
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.
其中,结点ListNode的 定义如下:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */
这题与83. Remove Duplicates from Sorted List有一些小差别,都是有一个已经排好序的链表,83题是要我们删除所有值重复的结点,使所有值只出现一次(1->1->2->3删为1->2->3),82题则是当一个值重复出现时,将全部值为该值的结点全部删去,只留全部不同的值的结点(1->1->2->3删为2->3)。
一种常见的思路为,使用循环,依此对链表中的每个结点进行判断和操作,当发现了一个值只出现了一次,把上一个只出现了一次的值的next指针指过来,指向新发现的只出现了一次的结点。如果没有只出现一次的结点,则返回一个NULL空指针。
为了方便处理,在输入的链表前面加了一个结点。参考代码如下:
class Solution {public: ListNode* deleteDuplicates(ListNode* head) { if(head == NULL || head->next == NULL) return head; ListNode* now = new ListNode(0); ListNode* first = now; now->next = head; ListNode* next = head; int count = 1; while(next != NULL){ if(next->next == NULL || next->val != next->next->val){ if(count == 1) { now->next = next; now = now->next; } count = 1; } else { count++; } next = next->next; } now->next = NULL; return first->next; }};
但其实这个问题也可以尝试使用递归来解决。使用循环略过所有重复的结点,当前不重复的结点的next指针指向递归求得的下一个不重复的结点。以后可以多考虑一下其他方法来解决问题。
class Solution {public: ListNode* deleteDuplicates(ListNode* head) { if(head == NULL || head->next == NULL) return head; int val = head->val; ListNode* temp = head->next; if(temp->val != val) { head->next = deleteDuplicates(temp); return head; } else { while(temp != NULL && temp->val == val) temp = temp->next; return deleteDuplicates(temp); } }};
阅读全文
0 0
- LeetCode题解 week15
- LeetCode 题解(Week15):22. Generate Parentheses
- Leetcode Week15
- leetcode week15
- LeetCode Week15: Word Ladder I
- week15-leetcode #122-BestTimetoBuyandSellStock II
- week15-leetcode #122-BestTimetoBuyandSellStock II
- week15
- LeetCode#445 Add Two Numbers II (week15)
- Leetcode: 73. Set Matrix Zeroes(Week15, Medium)
- Leetcode 647.Palindromic Substrings(算法分析week15)
- Leetcode 413. Arithmetic Slices(算法分析week15)
- 算法设计Week15 LeetCode Algorithms Problem #120 Triangle
- LeetCode#515 Find Largest Value in Each Tree Row (week15)
- [LeetCode-Algorithms-139] "Word Break" (2017.12.14-WEEK15)
- [LeetCode-Algorithms-128] "Longest Consecutive Sequence" (2017.12.14-WEEK15)
- leetcode题解
- leetcode题解
- 设计模式六大原则(2):里氏替换原则
- Mac中卸载根除paragon ntfs for mac软件【Mac手动卸载软件和插件】
- Qt 多界面来回切换的问题以及Qt界面关闭与销毁
- C++STL中的vector简要介绍
- 如何封装一个最简单的jquery插件
- LeetCode题解 week15
- Oracle静默安装
- 数据库导出数据模型图
- 输入三个字符串,按由小到大的顺序输出
- Tensorflow基础知识
- Android事件分发机制(最简图解:两张图搞明白)
- 初步了解DeepLearning----《一天搞懂深度学习》
- 内部类
- 常用函数