题解 | #删除有序链表中重复的元素-I#
删除有序链表中重复的元素-I
https://www.nowcoder.com/practice/c087914fae584da886a0091e877f2c79
这个题目还是非常基础的链表题目~
由于是删除重复的元素,所以使用哈希数组会非常方便。题目是说node->val的范围咋-100~100,所以我们设置一个201大小的数组作为哈希数组。其中-100对应的index就是0,0对应的是100,100对应的是200
这样我们可以仅仅遍历一次链表就可以了,设置一个tail指针=head->next,首先将hash[head->val+100]设置为1,然后对tail->val进行判断。
如果遇到hash[tail->val+100]==1,说明是重复的节点,则仅仅需要执行head->next = tail->next;free(tail);tail = head->next;即可。对了,这里忘记说,在非重复的情况下,head跟随tail向后移动~
注意的特殊情况就是1.head=NULL.2.初始请款下的head->next==NULL
struct ListNode* deleteDuplicates(struct ListNode* head ) {
// write code here
if(head==NULL)
{
return NULL;
}
int hash[201]={0};
struct ListNode* tail = head->next;
if(tail==NULL)
{
return head;
}
struct ListNode* out = head;
hash[head->val+100] = 1;
while(tail!=NULL)
{
if(hash[tail->val+100]==1)
{
head->next = tail->next;
free(tail);
tail = head->next;
}
else
{
hash[tail->val+100] = 1;
head = head->next;
tail = tail->next;
}
}
return out;
}
查看20道真题和解析