题目描述:
在一个排序的链表中,存在重复的节点,请删除该链表中重复的节点,重复的节点不保留,返回链表头指针。例如,,链表1->2->3->3->4->4->5 处理后为 1->2->5
【解1】使用HashMap记录每个节点是否重复出现,时间复杂度为O(N),空间复杂度为O(N)
1 import java.util.*; 2 3 /* 4 public class ListNode { 5 int val; 6 ListNode next = null; 7 8 ListNode(int val) { 9 this.val = val; 10 } 11 } 12 */ 13 public class Solution { 14 public ListNode deleteDuplication(ListNode pHead) 15 { 16 // 解法1:使用hashMap记录个数 17 if(pHead==null) 18 return pHead; 19 HashMap<Integer, Boolean> map = new HashMap<Integer, Boolean>(); 20 ListNode cur = pHead; 21 while(cur != null){ 22 if(map.containsKey(cur.val) == false){ 23 map.put(cur.val, true); 24 }else{ 25 map.put(cur.val, false); 26 } 27 cur = cur.next; 28 } 29 30 Set<Integer> set = map.keySet(); 31 boolean isfst = true; 32 ListNode pre = pHead; 33 for (int temp : set){ 34 if (map.get(temp) == true){ 35 if(isfst){ 36 pHead.val = temp; 37 isfst = false; 38 } 39 else{ 40 pre.next.val = temp; 41 pre = pre.next; 42 } 43 } 44 45 } 46 if(isfst) // 链表中只含有重复节点 47 return null; 48 else // 链表含有不重复的节点 49 pre.next = null; 50 return pHead; 51 } 52 }
【解2】每次找到一个不重复的节点,加入新的链表末尾,最后返回新链表的头指针,时间复杂度O(N),空间复杂度O(1)
1 import java.util.*; 2 3 /* 4 public class ListNode { 5 int val; 6 ListNode next = null; 7 8 ListNode(int val) { 9 this.val = val; 10 } 11 } 12 */ 13 public class Solution { 14 public ListNode deleteDuplication(ListNode pHead) 15 { 16 // 解法2:每次找一个不重复的元素,加入链表 17 if(pHead==null) 18 return pHead; 19 ListNode newhead = new ListNode(1); 20 ListNode index = newhead; 21 ListNode p = pHead; 22 boolean rept = false; 23 24 while(p!=null){ 25 rept = false; 26 while(p.next!=null && p.val == p.next.val){ 27 rept = true; 28 p = p.next; 29 } 30 if(rept == false){ 31 index.next = new ListNode(p.val); 32 index = index.next; 33 p = p.next; 34 }else{ 35 if(p.next == null){ 36 break; 37 }else{ 38 p = p.next; 39 } 40 } 41 } 42 43 return newhead.next; 44 } 45 }