DailyChallenge
面试题 02.01. 移除重复节点
20200626
难度:简单
题目描述
编写代码,移除未排序链表中的重复节点。保留最开始出现的节点。
示例1:
输入:[1, 2, 3, 3, 2, 1]
输出:[1, 2, 3]
示例2:
输入:[1, 1, 1, 1, 2]
输出:[1, 2]
提示:
链表长度在[0, 20000]范围内。
链表元素在[0, 20000]范围内。
进阶:
如果不得使用临时缓冲区,该怎么解决?
Solution
方法一:HashSet
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode removeDuplicateNodes(ListNode head) {
if(head == null) return null;
Set<Integer> set = new HashSet<>();
ListNode p = head;
set.add(head.val);
while(p.next != null){
ListNode cur = p.next;
if(!set.contains(cur.val)){
p.next = cur;
set.add(cur.val);
p = p.next;
}else{
p.next = cur.next;
}
}
return head;
}
}
方法二:如果不用临时缓冲区?这个时候需要增加时间复杂度。只能加一层循环
class Solution {
public ListNode removeDuplicateNodes(ListNode head) {
ListNode ob = head;
while (ob != null) {
ListNode oc = ob;
while (oc.next != null) {
if (oc.next.val == ob.val) {
oc.next = oc.next.next;
} else {
oc = oc.next;
}
}
ob = ob.next;
}
return head;
}
}
我的公众号:GitKid
暂时每日分享LeetCode,我在不断学习的过程中,公众号也在不断充实,欢迎大家扫码关注。
TODO:《剑指offer》系列