zoukankan      html  css  js  c++  java
  • [Leetcode 5] 83 Remove Duplicates from Sorted List

    Problem:

    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.

    Analysis:

    It's similar to the remove duplicates from sorted array problem. Use pointers ptrA and ptrB. ptrA always points to the last position of non-duplicated list and ptrB go through the list. One important thing is that we need a third point always points to the previous position of ptrB to delete duplicates. The third pointer can ensure that those duplicated nodes have no reference point to them and thus can be GC cleaned as soon as possible.

    The time complexity is O(n) and the space complexity is O(n)

    Code:

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) {
     *         val = x;
     *         next = null;
     *     }
     * }
     */
    public class Solution {
        public ListNode deleteDuplicates(ListNode head) {
            // Start typing your Java solution below
            // DO NOT write main() function
            if (head == null) return null;
            
            ListNode cur=head, valid=head, prev=null;
            
            while (cur.next != null) {
                prev = cur;
                cur = cur.next;
                if (cur.val != valid.val) {
                    if (prev.val == valid.val) prev.next=null;
                    valid.next = cur;
                    valid = cur;
                } else {
                  prev.next = null;
                }
            }
            
            return head;
        }
    }

    Attention:

    To access Java field, use . not ->

  • 相关阅读:
    笔记:一篇关于容器和虚拟机的对比
    语义化版本说明脑图
    KiCad EDA 5.1.4 发布了
    KiCad 5.1.4 无法覆铜?
    mac 常用的终端命令
    PC 商城扫描二维码登录
    Git的撤销与回滚
    springboot 集成elasticsearch5.4.3
    redis 缓存类型为map
    基于Elasticsearch 5.4.3的商品搜索系统
  • 原文地址:https://www.cnblogs.com/freeneng/p/3003323.html
Copyright © 2011-2022 走看看