LeetCode(83)Remove Duplicates from Sorted List
来源:互联网 发布:tv霸网络电视apk 编辑:程序博客网 时间:2024/06/10 08:30
题目如下:
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.
题目分析:
本题是给定一个链表,对链表进行滤重,使得每个数只出现一次。
和之前的一道题目 LeetCode(26)Remove Duplicates From Sorted Array 非常相似。之前这道题目是给定一个数组,对数组进行滤重,使得每个数只出现一次。
有了之前这倒题目的铺垫,使用相同的思路完成即可。核心思路是,理解为不断地去生成最终结果,即不断地把只出现过一次的元素加入到现有的结果中去更新最终结果。如果理解为在原来的基础上进行删除,就会做得比较麻烦了。特别是LeetCode(26)的数据结构为数组,每次删除都要把右侧数组左移,非常花时间。删除链表元素的时间开销虽然小于删除数组元素的时间开销,但是使用生成而非删除这样的思路还是不错的。
代码如下:
//84ms过大集合class Solution {public: ListNode *deleteDuplicates(ListNode *head) { if(head==NULL||head->next==NULL) return head; ListNode* p=head; ListNode* q=head->next; while(q!=NULL){ if(q->val==p->val) { q=q->next; }else{ p->next=q; p=q; q=q->next; } } p->next=NULL; return head; }};
update 1: 2014 - 10- 07
用生成新数组的思路,重构
class Solution {public: ListNode *deleteDuplicates(ListNode *head) { if(head==NULL) return head; ListNode* p=head; ListNode* q=head->next; while(q!=NULL){ if(q->val==p->val) { p->next = q->next; }else{ p=q; } q = q->next; } return head; }};
另外一种写法基本一样, 只是变量名更清楚,是这样的:
class Solution {public: ListNode *deleteDuplicates(ListNode *head) { if (head == NULL) return head; ListNode* p_current = head; ListNode* p_next = head->next; while (p_current != NULL && p_next != NULL) { if (p_current->val == p_next-> val) { p_current->next = p_next->next; } else { p_current = p_current->next; } p_next = p_next->next; } return head; }};
0 0
- LeetCode(83)Remove Duplicates from Sorted List
- [leetcode 83]Remove Duplicates from Sorted List
- [leetcode]83 Remove Duplicates from Sorted List
- [leetcode 83]Remove Duplicates from Sorted List
- leetcode-83 Remove Duplicates from Sorted List
- leetcode || 83、Remove Duplicates from Sorted List
- LeetCode 83 Remove Duplicates from Sorted List
- LeetCode---(83) Remove Duplicates from Sorted List
- leetcode 83 Remove Duplicates from Sorted List
- LeetCode 83:Remove Duplicates from Sorted List
- leetcode[83]:Remove Duplicates from Sorted List
- Leetcode[83]-Remove Duplicates from Sorted List
- Leetcode #83 Remove Duplicates from Sorted List
- leetcode 83: Remove Duplicates from Sorted List
- leetcode: (83) Remove Duplicates from Sorted List
- [Leetcode]#83 Remove Duplicates from Sorted List
- LeetCode 83 - Remove Duplicates from Sorted List
- [LeetCode-83] Remove Duplicates from Sorted List
- 尊重是相对的
- Geeks 面试题: Rat in a Maze 回溯法解迷宫
- 持之以恒方显成就
- 2013年终总结
- 硬件和核数量的意义2014
- LeetCode(83)Remove Duplicates from Sorted List
- 场解决方案添加webpart(Create Webpart to page using code)
- Spring Security3.1 最新配置实例
- 编写第一个Android运行程序
- 学习贴——如何减少数码照片的噪点
- Raphael一个js编写的网页矢量图形库
- virtual operator 虚操作符重载的应用
- QT安装环境
- Button