编写代码,移除未排序链表中的重复节点。保留最开始出现的节点。
示例1:
输入:[1, 2, 3, 3, 2, 1]
输出:[1, 2, 3]
示例2:
输入:[1, 1, 1, 1, 2]
输出:[1, 2]
提示:
- 链表长度在[0, 20000]范围内。
- 链表元素在[0, 20000]范围内。
进阶:
如果不得使用临时缓冲区,该怎么解决?
分析:
方法1:哈希表
利用集合存储遍历过的节点,当遍历到重复节点时删除即可。
时间复杂度:O(n)
空间复杂度:O(n)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode removeDuplicateNodes(ListNode head) {
//创建集合
HashSet<Integer> set = new HashSet<>();
//定义遍历的头节点
ListNode pre = new ListNode(0);
pre.next = head;
//遍历链表
while(pre.next != null){
//节点重复
if(set.contains(pre.next.val)){
//删除该节点
pre.next = pre.next.next;
}
//当前节点变上一节点
else{
//记录
set.add(pre.next.val);
//遍历下一个节点
pre = pre.next;
}
}
return head;
}
}
方法2:暴力解法
不得使用临时缓冲区就只能暴力解法,两层循环依次遍历。
时间复杂度:O(n^2)
空间复杂度:O(1)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode removeDuplicateNodes(ListNode head) {
//遍历
for(ListNode i = head; i != null; i = i.next){
ListNode j = i;
while(j.next != null){
//重复
if(i.val == j.next.val){
j.next = j.next.next;
}
else{
j = j.next;
}
}
}
return head;
}
}
题目来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-duplicate-node-lcci