面试题 02.01. 移除重复节点
编写代码,移除未排序链表中的重复节点。保留最开始出现的节点。
示例1:
输入:[1, 2, 3, 3, 2, 1]
输出:[1, 2, 3]
示例2:
输入:[1, 1, 1, 1, 2]
输出:[1, 2]
提示:
- 链表长度在[0, 20000]范围内。
- 链表元素在[0, 20000]范围内。
进阶:
如果不得使用临时缓冲区,该怎么解决?
官方题解:
//方法一:空间换时间 时O(n) -> 空O(n)
class Solution{
public ListNode removeDuplicateNodes(ListNode head){
if(head==null) return head;
Set<Integer> set = new HashSet<>();
ListNode cur = head;
set.add(cur.val);
while(cur.next!=null){
ListNode node = cur.next;
if(set.add(node.val)){//添加成功说明没有重复元素
cur = cur.next;
}else{//否则说明cur.next出现重复,直接去掉
cur.next = cur.next.next;
}
}
cur.next = null;
return head;
}
}
//方法二:时间换空间 时O(n^2) -> 空O(1)
class Solution{
public ListNode removeDuplicateNodes(ListNode head){
if(head==null) return head;
ListNode cur = head;
while(cur!=null){
ListNode node = cur; //采用双指针进行遍历
//每一个节点都和后面所有节点比较,从而去重
while(node.next!=null){
if(node.next.val == cur.val){
node.next = node.next.next;
}else{
node = node.next;
}
}
cur = cur.next;
}
return head;
}
}