题意
如题
题解
使用 HashSet.
时间复杂度 O(n), 额外空间复杂度 O(n).
todo
使用选择排序也可以做.
代码
- import java.util.HashSet;
- public class Main {
- public static void main(String args[]) {
- // 测试
- Node n1=new Node(2);
- Node n2=new Node(2);
- Node n3=new Node(3);
- n1.next=n2;
- n2.next=n3;
- Node head=n1;
- rmRepeat(head);
- // 测试
- Node pNode=head;
- while(pNode!=null) {
- System.out.println(pNode.val);
- pNode=pNode.next;
- }
- }
- public static void rmRepeat(Node head) {
- if(head==null) {
- return;
- }
- HashSet<Integer> hashset=new HashSet();
- hashset.add(head.val);
- Node pre=head;
- Node cur=pre.next;
- while(cur!=null) {
- if(hashset.contains(cur.val)) {
- pre.next=cur.next;
- }
- else {
- hashset.add(cur.val);
- pre=cur;
- }
- cur=cur.next;
- }
- }
- }
[程序员代码面试指南] 链表问题 - 删除无序链表中重复出现的节点
来源: http://www.bubuko.com/infodetail-3078687.html