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)。
相关推荐
2301_8227032024 分钟前
鸿蒙Flutter第三方库FlutterUnit组件百科适配——具体示例还原演示1
算法·flutter·华为·harmonyos·鸿蒙
2301_764441337 小时前
LISA时空跃迁分析,地理时空分析
数据结构·python·算法
东北洗浴王子讲AI7 小时前
GPT-5.4辅助算法设计与优化:从理论到实践的系统方法
人工智能·gpt·算法·chatgpt
Billlly8 小时前
ABC 453 个人题解
算法·题解·atcoder
玉树临风ives8 小时前
atcoder ABC 452 题解
数据结构·算法
feifeigo1238 小时前
基于马尔可夫随机场模型的SAR图像变化检测源码实现
算法
fengfuyao9858 小时前
基于STM32的4轴步进电机加减速控制工程源码(梯形加减速算法)
网络·stm32·算法
无敌昊哥战神10 小时前
深入理解 C 语言:巧妙利用“0地址”手写 offsetof 宏与内存对齐机制
c语言·数据结构·算法
小白菜又菜10 小时前
Leetcode 2075. Decode the Slanted Ciphertext
算法·leetcode·职场和发展
Proxy_ZZ010 小时前
用Matlab绘制BER曲线对比SPA与Min-Sum性能
人工智能·算法·机器学习