zoukankan      html  css  js  c++  java
  • lc面试准备:Remove Duplicates from Sorted List II

    1 题目

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

    For example,
    Given 1->2->3->3->4->4->5, return 1->2->5.
    Given 1->1->1->2->3, return 2->3.

    接口

    ListNode deleteDuplicates(ListNode head) 

    把出现重复的元素全部删除。

    2 思路

    双指针。把前驱指针指向上一个不重复的元素中,如果找到不重复元素,则把前驱指针知道该元素,否则删除此元素。另一个指针遍历。

    细节实现有挺多地方需要注意的:

    ① 1个while循环条件 pCur != null

    ② 寻找不重复的元素 while循环条件 pCur.next != null && prev.next.val == pCur.next.val

    复杂度

    Time: O(n)
    Space: O(1)

    3 代码

     1     public ListNode deleteDuplicates(ListNode head) {
     2         if(head == null)
     3             return head;
     4         ListNode dummy = new ListNode(Integer.MAX_VALUE);
     5         dummy.next = head;
     6         ListNode prev = dummy;
     7         ListNode pCur = head;
     8         while (pCur != null)
     9         {
    10             while(pCur.next != null && prev.next.val == pCur.next.val){
    11                 pCur = pCur.next;
    12             }
    13             if(prev.next == pCur){ // 找到单独的元素
    14                 prev = prev.next;
    15             } else{ // 剔除重复的元素
    16                 prev.next = pCur.next;
    17             }
    18             pCur = pCur.next;
    19         }
    20         return dummy.next;
    21     }

    4 总结

    思路和Remove Duplicates from Sorted List一样,但是细节实现更多。

    5 扩展

    如何从排序数组中去除重复的元素?

    6 参考

    1. leetcode
    2. Code Ganker征服代码
     
  • 相关阅读:
    (转)当你输入一个网址,实际会发生什么?
    Word Ladder II
    Jump Game II
    Candy
    [生成树][Uva1395][Slim Span]
    [AC自动机][HDU3065]
    [KMP求最小循环节][HDU3746][Cyclic Nacklace]
    [扩展KMP][HDU3613][Best Reward]
    [Manacher][HDU3613][Best Reward]
    [KMP][HDU3336][Count the string]
  • 原文地址:https://www.cnblogs.com/byrhuangqiang/p/4317938.html
Copyright © 2011-2022 走看看