数组和链表中,原地去除重复元素的题型归纳和总结

26. 数组:删除排序数组中的重复项
在这里插入图片描述

利用双指针的方法:

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;
    }
};

83. 链表:删除排序链表中的重复元素
在这里插入图片描述

/**
 * 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;
    }
};

猜你喜欢

转载自blog.csdn.net/cckluv/article/details/110874590
今日推荐