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征服代码
     
  • 相关阅读:
    MFC框架程序实现十一
    MFC框架程序实现八
    MFC框架程序实现十二
    在Visual C++中如何利用UDL文件来建立ADO连接
    OnePage收集 HA
    微博跳转的url HA
    淘宝iosapp调用规范 HA
    Excel操作相关 HA
    C#GDI+编程基础 HA
    html5deoms HA
  • 原文地址:https://www.cnblogs.com/byrhuangqiang/p/4317938.html
Copyright © 2011-2022 走看看