[LeetCode] 82. Remove Duplicates from Sorted List II

Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well.

Example 1:

Input: head = [1,2,3,3,4,4,5]
Output: [1,2,5]

Example 2:

Input: head = [1,1,1,2,3]
Output: [2,3]

Constraints:

  • The number of nodes in the list is in the range [0, 300].
  • -100 <= Node.val <= 100
  • The list is guaranteed to be sorted in ascending order.

删除排序链表中的重复元素II。

题意跟版本一很接近,唯一的区别是,版本一是请你删除重复元素,使得 output 里面每个元素只出现一次。版本二是请你删除所有出现超过一次的元素。思路是需要创建一个 dummy 节点,放在所有需要遍历的节点之前,遍历的时候,找是否有两个节点的 val 相同,找到后记下这个 val。再往后遍历的时候,只要遇到这个 val 就跳过。

比如第一个例子好了,当cur遍历到2的时候,cur.next == 3, cur.next.next == 3;此时记录sameVal = cur.next.val。接着从cur.next开始判断,只要cur.next.val == 3的时候,就cur.next = cur.next.next。

如果是比如一开始遍历到1的时候好了,此时cur.next == 2,cur.next.next == 3,两者并不相等,所以直接就遍历下一个节点,cur = cur.next。

时间O(n)

空间O(1)

JavaScript实现

 1 /**
 2  * @param {ListNode} head
 3  * @return {ListNode}
 4  */
 5 var deleteDuplicates = function(head) {
 6     // corner case
 7     if (head === null || head.next === null) return head;
 8 
 9     // normal case
10     let dummy = new ListNode(0);
11     dummy.next = head;
12     let cur = dummy;
13     while (cur.next !== null && cur.next.next !== null) {
14         if (cur.next.val === cur.next.next.val) {
15             let sameVal = cur.next.val;
16             while (cur.next !== null && cur.next.val === sameVal) {
17                 cur.next = cur.next.next;
18             }
19         } else {
20             cur = cur.next;
21         }
22     }
23     return dummy.next;
24 };

 

Java实现

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 class Solution {
10     public ListNode deleteDuplicates(ListNode head) {
11         // corner case
12         if (head == null || head.next == null) {
13             return head;
14         }
15 
16         // normal case
17         ListNode dummy = new ListNode(0);
18         dummy.next = head;
19         // 注意这里cur是从dummy开始
20         ListNode cur = dummy;
21         while (cur.next != null && cur.next.next != null) {
22             if (cur.next.val == cur.next.next.val) {
23                 int sameVal = cur.next.val;
24                 while (cur.next != null && cur.next.val == sameVal) {
25                     cur.next = cur.next.next;
26                 }
27             } else {
28                 cur = cur.next;
29             }
30         }
31         return dummy.next;
32     }
33 }

 

相关题目

83. Remove Duplicates from Sorted List

82. Remove Duplicates from Sorted List II

1836. Remove Duplicates From an Unsorted Linked List

LeetCode 题目总结

posted @ 2019-11-08 03:24  CNoodle  阅读(433)  评论(0编辑  收藏  举报