LC——移除重复节点
题目链接:https://leetcode-cn.com/problems/remove-duplicate-node-lcci/
编写代码,移除未排序链表中的重复节点。保留最开始出现的节点。
示例1:
输入:[1, 2, 3, 3, 2, 1]
输出:[1, 2, 3]
思路:
其实就是去重,想到集合Set就是可以用来去重。一开始想的是通过HashSet来存,然后遍历去取值,但是HashSet是无序的(存入的顺序和取的顺序不一样),然后想起LinkHashSet是有序的(存入的顺序和取的顺序一样)。
后来想起之前做的一个题目,进行了修改,这里就不用存值再取值了,通过引入第二个ListNode来进行操作。
通过测试,HashSet的运行时间和内存消耗是相对少的。
代码:
public static ListNode removeDuplicateNodes(ListNode head) {
if(head == null){
return null;
}
ListNode listNode = new ListNode(head.val);
ListNode temp = listNode;
Collection collection = new HashSet();
while (head != null){
if(!collection.contains(head.val)){
collection.add(head.val);
temp.next = new ListNode(head.val);
temp = temp.next;
}
head = head.next;
}
return listNode.next;
}
主方法:
public static void main(String[] args){
ListNode l = new ListNode(1,new ListNode(1,new ListNode(2,new ListNode(3,new ListNode(2,new ListNode(1))))));
System.out.println("---------="+removeDuplicateNodes(l).toString());
}
ListNode类代码:
public class ListNode {
public int val;
public ListNode next;
public ListNode() {
}
public ListNode(int val) {
this.val = val;
}
public ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
public int getVal() {
return val;
}
public void setVal(int val) {
this.val = val;
}
public ListNode getNext() {
return next;
}
public void setNext(ListNode next) {
this.next = next;
}
@Override
public String toString() {
return "ListNode{" +
"val=" + val +
", next=" + next +
'}';
}
}