- leetcode题目
1.1题目描述
1.2知识点及思路
1.3代码 - 总结
一.leetcode题目
1.Remove all elements from a linked list of integers that have value val.
题目描述:删除链表中指定值得结点,并返回头结点
知识点:链表查找;链表删除
注意情况:①第一个值是需删除元素②链表头结点变化
代码如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* removeElements(ListNode* head, int val)
{
if(!head)
return head;
while(head->val==val)
{
head=head->next;
if(!head)
return head;
}
ListNode*p=head->next;
ListNode*pre=head;
while (p)
{
if(p->val==val)
{
pre->next=p->next;
p=pre->next;
}
else
{
pre=p;
p=p->next;
}
}
return head;
}
};
2.Remove Duplicates from Sorted Array
题目描述:移除排序数组中的副本,并返回数组长度
知识点:数组的遍历及算法优化
思路:①用key保存前一个数组元素的值②用变量xiaBiao更新数组下标,使得③xiaBiao++操作后保存值不同于key
代码如下:
class Solution {
public:
int removeDuplicates(vector<int>& nums)
{
if(nums.size()<=1)
return nums.size();
int key=nums[0];
int xiaBiao=1;
for(int i=1;i<nums.size();i++)
{
if(nums[i]!=key)
{
nums[xiaBiao]=nums[i];
key=nums[xiaBiao];
xiaBiao++;
}
}
return xiaBiao;
}
};
二.总结
I.题目简单,但是要注意边界处理,保证代码的robust.II让我们一同努力,明天会更好!