Given a sorted linked list, delete all duplicates such that each element appear only once.
Example 1:
Input: 1->1->2 Output: 1->2
Example 2:
Input: 1->1->2->3->3 Output: 1->2->3
本题是个基础链表去重题,Accepted代码如下:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode a = head;
while (a != null) {
if (a.next == null) {
return head;
} else if (a.val == a.next.val) {
a.next = a.next.next;
} else {
a = a.next;
}
}
return head;
}
}
本解法空间复杂度超过所有,时间复杂度仅超过26.74%,但看了一些排名靠前的解法,均未发现其有何时间的优越之处,很多思路类似。
本文介绍了一种在给定已排序链表中删除所有重复元素的算法,确保每个元素只出现一次。通过迭代检查相邻节点值,如果相同则跳过重复节点,最终返回处理后的链表头。该算法在时间复杂度上表现一般,但在空间复杂度上具有优势。
736

被折叠的 条评论
为什么被折叠?



