Killing LeetCode [82] 删除排序链表中的重复元素 II

Description

给定一个已排序的链表的头 head , 删除所有重复的元素,使每个元素只出现一次 。返回 已排序的链表 。

Intro

Ref Link:https://leetcode.cn/problems/remove-duplicates-from-sorted-list-ii/

Difficulty:Medium

Tag:LinkedList

Updated Date:2023-08-02

Test Cases

示例1:

输入:head = [1,2,3,3,4,4,5]
输出:[1,2,5]

示例 2:

输入:head = [1,1,1,2,3]
输出:[2,3]

提示:

链表中节点数目在范围 [0, 300] 内
-100 <= Node.val <= 100
题目数据保证链表已经按升序 排列

思路

  • 链表遍历

Code AC

class Solution {
    /**
     * test case
     * 1 1 1   =====> null
     * 1 1 2   =====> 2
     */
    public ListNode deleteDuplicates(ListNode head) {
        if (head == null) return head;
        ListNode preHead = new ListNode(-1);
        preHead.next = head;
        ListNode cur = preHead;

        while (cur.next != null) {
            ListNode pivot = cur.next; // might be deleted, need define pivot tmp node here
            while (pivot.next != null && pivot.val == pivot.next.val)
                pivot = pivot.next;
            if (cur.next == pivot)  // if no same val nodes, means not run into while loop, then cur moves to next 
                cur = cur.next;
            else                    // else cur.next need to be updated to pivot,next
                cur.next = pivot.next;
        }
        return preHead.next;
    }
}

Accepted

166/166 cases passed (0 ms)
Your runtime beats 100 % of java submissions
Your memory usage beats 65.52 % of java submissions (41.5 MB)

复杂度分析

  • 时间复杂度:O(n),其中 n 是链表的长度。
  • 空间复杂度:O(1)。
相关推荐
01_36 分钟前
力扣hot100——LRU缓存(面试高频考题)
leetcode·缓存·面试·lru
菜鸟一枚在这1 小时前
深度解析建造者模式:复杂对象构建的优雅之道
java·开发语言·算法
gyeolhada1 小时前
2025蓝桥杯JAVA编程题练习Day5
java·数据结构·算法·蓝桥杯
阿巴~阿巴~1 小时前
多源 BFS 算法详解:从原理到实现,高效解决多源最短路问题
开发语言·数据结构·c++·算法·宽度优先
给bug两拳1 小时前
Day9 25/2/22 SAT
算法
_Itachi__2 小时前
LeetCode 热题 100 73. 矩阵置零
算法·leetcode·矩阵
夏末秋也凉2 小时前
力扣-贪心-376 摆动序列
算法·leetcode
Orange--Lin3 小时前
【用deepseek和chatgpt做算法竞赛】——还得DeepSeek来 -Minimum Cost Trees_5
人工智能·算法·chatgpt
01_3 小时前
力扣hot100 ——搜索二维矩阵 || m+n复杂度优化解法
算法·leetcode·矩阵