82.删除排序链表中的重复元素II
先获取重复的val,存放到Set中,然后再遍历,如果是是重复的数据则跳过。
1
/**
2
* Definition for singly-linked list.
3
* public class ListNode {
4
* int val;
5
* ListNode next;
6
* ListNode(int x) { val = x; }
7
* }
8
*/
9
class Solution {
10
Set<Integer> set = new HashSet<>();
11
12
public ListNode deleteDuplicates(ListNode head) {
13
if(head == null){
14
return null;
15
}
16
//避免递归重复调用
17
if(set.isEmpty()){
18
ListNode next = head.next;
19
int val = head.val;
20
while(next != null){
21
if(val == next.val){
22
set.add(val);
23
}
24
val = next.val;
25
next = next.next;
26
}
27
}
28
//如果集合为空说明不存在重复的元素直接返回
29
if(set.isEmpty()){
30
return head;
31
}
32
while (head != null && set.contains(head.val)) {
33
head = head.next;
34
}
35
if(head != null)
36
head.next = deleteDuplicates(head.next);
37
return head;
38
}
39
}
Copied!
最近更新 1yr ago
复制链接