友情支持

如果您觉得这个笔记对您有所帮助,看在D瓜哥码这么多字的辛苦上,请友情支持一下,D瓜哥感激不尽,😜

支付宝

微信

有些打赏的朋友希望可以加个好友,欢迎关注D 瓜哥的微信公众号,这样就可以通过公众号的回复直接给我发信息。

wx jikerizhi

公众号的微信号是: jikerizhi因为众所周知的原因,有时图片加载不出来。 如果图片加载不出来可以直接通过搜索微信号来查找我的公众号。

82. Remove Duplicates from Sorted List II

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

Example 1:
Input: 1->2->3->3->4->4->5
Output: 1->2->5
Example 2:
Input: 1->1->1->2->3
Output: 2->3

解题分析

快慢指针是个好办法!

注意推敲满指针前进的条件!

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
 * Runtime: 1 ms, faster than 60.61% of Java online submissions for Remove Duplicates from Sorted List II.
 * Memory Usage: 39.4 MB, less than 6.98% of Java online submissions for Remove Duplicates from Sorted List II.
 *
 * Copy from: https://leetcode.cn/problems/remove-duplicates-from-sorted-list-ii/solutions/7396/kuai-man-zhi-zhen-by-powcai-2/[递归与非递归 - 删除排序链表中的重复元素 II - 力扣(LeetCode)]
 */
public ListNode deleteDuplicates(ListNode head) {
    ListNode dummy = new ListNode(0);
    dummy.next = head;
    ListNode slow = dummy;
    ListNode fast = dummy;
    while (Objects.nonNull(fast)) {
        while (Objects.nonNull(fast.next) && fast.val == fast.next.val) {
            fast = fast.next;
        }
        if (slow.next == fast) {
            slow = slow.next;
        } else {
            slow.next = fast.next;
        }
        fast = fast.next;
    }
    return dummy.next;
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
 * 参考官方题解
 */
public ListNode deleteDuplicates(ListNode head) {
  if (head == null || head.next == null) {
    return head;
  }
  ListNode dummy = new ListNode();
  dummy.next = head;
  ListNode cur = dummy;
  while (cur.next != null && cur.next.next != null) {
    if (cur.next.val == cur.next.next.val) {
      // 将重复元素全部删除
      int val = cur.next.val;
      while (cur.next != null && cur.next.val == val) {
        cur.next = cur.next.next;
      }
    } else {
      cur = cur.next;
    }
  }
  return dummy.next;
}