利用雙指針的方法:
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if(nums.size()==0)
return 0;
int slow=0;
int fast=0;
for(fast=0;fast<nums.size()-1;fast++)
{
if(nums[fast]!=nums[fast+1])
{
nums[++slow]=nums[fast+1];
}
}
return slow+1;
}
};
27.數組: 移除元素
同理上面的方法:
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int slow=0;
int fast=0;
while(fast<nums.size())
{
if(nums[fast]==val)
{
++fast;
}
else
{
nums[slow]=nums[fast];
++slow;
++fast;
}
}
return slow;
}
};
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
class Solution {
public:
/**
*
* @param head ListNode類
* @return ListNode類
*/
ListNode* deleteDuplicates(ListNode* head) {
// write code here
if(head==NULL)
return head;
ListNode* Dummy=new ListNode(-1);
Dummy->next=head;
ListNode* fast=Dummy;
ListNode* fastpre=Dummy;
while(fast!=NULL && fast->next!=NULL)
{
if(fast->val!=fast->next->val)
{
fastpre=fast;
fast=fast->next;
}
else
{
while(fast->next!=NULL && fast->val==fast->next->val)
{
fast=fast->next;
}
fast=fast->next;
fastpre->next=fast;
}
}
return Dummy->next;
}
};
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if(head==NULL)
return head;
ListNode* slow=head;
ListNode* fast=head;
while(fast->next!=NULL)
{
if(fast->val!=fast->next->val)
{
slow=slow->next;
slow->val=fast->next->val;
}
fast=fast->next;
}
slow->next=NULL;
return head;
}
};