介绍:
去掉集合中,相邻重复元素的问题,无论集合是 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 中重复