Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2
, return 1->2
.
Given 1->1->2->3->3
, return 1->2->3
.
Solution:
稍微修改上一个代码即可,遇到次数多于1的,先输出一个,然后将hashmap中标记一下(这里我就是将其value改为0),后面就不输出它即可。
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { 7 * val = x; 8 * next = null; 9 * } 10 * } 11 */ 12 public class Solution { 13 public ListNode deleteDuplicates(ListNode head) { 14 // Start typing your Java solution below 15 // DO NOT write main() function 16 HashMap<Integer,Integer> map = new HashMap<Integer,Integer>(); 17 ListNode cur = head; 18 while(cur != null){ 19 if(map.containsKey(cur.val)){ 20 map.put(cur.val,map.get(cur.val) + 1); 21 }else{ 22 map.put(cur.val,1); 23 } 24 cur = cur.next; 25 } 26 ListNode header = new ListNode(-1); 27 header.next = head; 28 cur = header; 29 while(cur.next != null){ 30 if(map.get(cur.next.val) > 1){ 31 map.put(cur.next.val,0); 32 cur = cur.next; 33 } 34 else if(map.get(cur.next.val) == 1){ 35 cur = cur.next; 36 }else{ 37 cur.next = cur.next.next; 38 } 39 } 40 return header.next; 41 } 42 }
我发现可以简化。。。
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { 7 * val = x; 8 * next = null; 9 * } 10 * } 11 */ 12 public class Solution { 13 public ListNode deleteDuplicates(ListNode head) { 14 // Start typing your Java solution below 15 // DO NOT write main() function 16 HashMap<Integer,Integer> map = new HashMap<Integer,Integer>(); 17 ListNode header = new ListNode(-1); 18 header.next = head; 19 ListNode cur = header; 20 while(cur.next != null){ 21 if(map.containsKey(cur.next.val)){ 22 cur.next = cur.next.next; 23 }else{ 24 map.put(cur.next.val,1); 25 cur = cur.next; 26 } 27 } 28 return header.next; 29 } 30 }
第二遍: 由于linkedlist 已经被sorted,所以可以直接用双指针来完成。使用constant extra space。
1 public class Solution { 2 public ListNode deleteDuplicates(ListNode head) { 3 // Start typing your Java solution below 4 // DO NOT write main() function 5 int value = Integer.MAX_VALUE; 6 ListNode cur = head, per = head; 7 while(per != null){ 8 if(per.val != value){ 9 value = per.val; 10 cur = per; 11 per = per.next; 12 }else{ 13 per = per.next; 14 cur.next = per; 15 } 16 } 17 return head; 18 } 19 }