[Leetcode学习-c++&java]Remove Duplicates IN String&Array&List

这篇博客介绍了如何使用C++和Java解决LeetCode中的几个问题,涉及删除有序List、Array和String中相邻的重复元素。通过三指针法解决这些问题,包括Remove Duplicates from Sorted List II、Remove Duplicates from Sorted List、Remove Duplicates from Sorted Array II和Remove All Adjacent Duplicates in String II等题目。
摘要由CSDN通过智能技术生成

介绍:

去掉集合中,相邻重复元素的问题,无论集合是 string(string 是 char 数组来的) array list 都有相似思路,就是用三指针来解决,所以都放到一块了,首先是 list 的指针处理,引出了对 array string 这两种集合的处理思路。


List:

问题1:Remove Duplicates from Sorted List II

难度:medium

说明:

下面题目的解题思路都是从这题来的,给出一个 list 输入,然后将 list 中有数值重复两次以上的所有节点删除掉, list 是有序的。

题目连接:https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/

输入范围:

  • The number of nodes in the list is in the range [0, 300].
  • -100 <= Node.val <= 100
  • The list is guaranteed to be sorted in ascending order.

输入案例:

Example 1:
Input: head = [1,2,3,3,4,4,5]
Output: [1,2,5]

Example 2:
Input: head = [1,1,1,2,3]
Output: [2,3]

我的代码:

这里的话,首先想到两个指针,一个前一个后就能够对比节点数值,找出重复了两次的节点。但是依然缺少一个在重复节点之前那个节点的指针,所以再加多一个拼接指针,指向 list 的拼接末尾,然后再来一个 dummy 隐藏的头节点,存放删除后 list 的头结点,一共三指针就可以处理了。

然后还需要一个标记 flag 记录 避免一前一后指针遇到 两组 重复节点, 拼接指针就傻傻地往后走了。

Java:

class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        ListNode dummy = new ListNode(-101), next = dummy, pre = dummy; // 隐藏节点开始出发
        dummy.next = head;
        boolean flag = false; // 用一个记录标记
        while(head != null) {
            if(head.val == pre.val) {
                pre = head;
                head = head.next;
                flag = false;
            } else {
                if(flag) next = next.next; // 相当于第二次没找到重复节点,才让拼接指针往后移动
                pre = head;
                next.next = pre;
                head = head.next;
                flag = true;
            }
        }
        if(!flag) next.next = null;
        return dummy.next;
    }
}

C++:

class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        ListNode *dummy = new ListNode(-101), *next = dummy, *pre = dummy;
        bool flag = false;
        dummy -> next = head;
        while(head != nullptr) {
            if(head -> val == pre -> val) {
                pre = head;
                head = head -> next;
                flag = false;
            } else {
                pre = head;
                head = head -> next;
                if(flag) next = next-> next;
                next -> next = pre;
                flag = true;
            }
        }
        if(!flag) next -> next = nullptr;
        return dummy -> next;
    }
};

问题2:Remove Duplicates from Sorted List

难度:easy

说明:

只需要删除 list 中重复

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值