LeetCode 83. Remove Duplicates from Sorted List (从有序链表中去除重复项)
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
.
题目标签:Linked List
题目给了我们一个 list,让我们去除中间的重复项。
设一个 cursor = head,遍历list,每一次比较 cursor 和 cursor.next,如果一样,发现重复项,把cursor link 到 next next node 即可;如果不一样,移动cursor到下一个点。
Java Solution:
Runtime beats 18.22%
完成日期:06/09/2017
关键词:singly-linked list
关键点:比较cursor 和 cursor.next,一样就把cursor link 到 next next node。
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 class Solution 10 { 11 public ListNode deleteDuplicates(ListNode head) 12 { 13 ListNode cursor = head; 14 15 while(cursor != null) 16 { 17 if(cursor.next != null && cursor.val == cursor.next.val) // if find a duplicate one 18 { 19 ListNode duplicate = cursor.next; 20 21 cursor.next = duplicate.next; // link to next next one, skip this duplicate 22 duplicate.next = null; 23 } 24 else 25 cursor = cursor.next; 26 27 } 28 29 return head; 30 } 31 }
参考资料:N/A
LeetCode 题目列表 - LeetCode Questions List
题目来源:https://leetcode.com/
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
· ThreeJs-16智慧城市项目(重磅以及未来发展ai)
· 软件产品开发中常见的10个问题及处理方法
· Vite CVE-2025-30208 安全漏洞
· 互联网不景气了那就玩玩嵌入式吧,用纯.NET开发并制作一个智能桌面机器人(四):结合BotSharp
· MQ 如何保证数据一致性?