题目
编写代码,移除未排序链表中的重复节点。保留最开始出现的节点。
题目链接:link.
分析
本题考链表,要去掉所有重复的节点,需要两步,首先判断这个节点是否重复,如果重复,将这个节点去掉。可以双重循环去重(题目进阶),也可以用空间换时间,只要一重循环就可以完成。
题解
定义链表
public class ListNode {
public int val;
public ListNode next;
ListNode(int x){
this.val = x;
}
@Override
public String toString() {
return "ListNode{" +
"val=" + val +
", next=" + next +
'}';
}
}
数组存储
题目已知链表的数值范围是0-20000,可以直接用一个20001长的数组存储链表的特征。
public static ListNode removeDuplicateNodes(ListNode head){
if(head == null || head.next==null) return head;
ListNode pre = head;
ListNode cur = head.next; // 使用两个指针来去重
int[] a = new int[20001]; // 数组存储所有已经出现的数,初始为0
a[head.val] += 1;
while(cur != null){
if(a[cur.val]!=0){ // 重复节点
a[cur.val] += 1;
pre.next = cur.next; // 去除cur节点
cur = pre.next; // pre不动,cur往后移
}
else{ // 不重复节点
a[cur.val] += 1;
pre = cur;
cur = pre.next; // pre,cur都往后移
}
}
return head;
}
总结
题目的进阶要求是不适用临时缓冲区,就是暴力法,但是那样的话时间复杂度就是O(n2),据说会超时,hhh。