我觉得我还是要注重一下时间的复杂度,不然怎么叫搞算法。。
题目:
给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
示例 1:
输入: 1->1->2
输出: 1->2
示例 2:
输入: 1->1->2->3->3
输出: 1->2->3
思路解答:这个题是一个已经排好序的链表了,所以只需要挨个比较删除就好了。不需要整个的去遍历。
C语言实现(一):
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* deleteDuplicates(struct ListNode* head) {
struct ListNode *p1=head;
struct ListNode *p2=p1->next;
int val_1=p1->val;
while(p1->next!=NULL){
if(val_1==p2->val){
if(p2->next==NULL){
p1->next=NULL;
return head;
}
else
p2=p2->next;
}
p1->next=p2;
p1=p1->next;
}
return head;
}
时间复杂度过高,导致提交审核不过,时间超出限制。
还需要优化
改进版本:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* deleteDuplicates(struct ListNode* head) {
struct ListNode *p1=head;
if((p1==NULL)||(p1->next==NULL))//必须先判断p1==NULL
return head;
else{
while(p1->next!=NULL&&p1!=NULL){
if(p1->val==p1->next->val){
p1->next=p1->next->next;
}
else
p1=p1->next;
}
return head;
}
}
结果:
执行用时 : 12 ms, 在Remove Duplicates from Sorted List的C提交中击败了84.69% 的用户
内存消耗 : 7.5 MB, 在Remove Duplicates from Sorted List的C提交中击败了0.76% 的用户
这里面当时有个leetcode报错:member access within null pointer of type 'struct ListNode'
错误出现原因错误出现原因: 因为试图使用空指针。
解决方法解决方法:增加判断条件,排除对空指针的引用。(一定要注意,我一直以为我排除了所有空指针的情况,其实并没有)其实我就是先判断了p1->next==NULL,但是实际上是应该先判断p1==NULL。调整一下顺序就OK了