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%,但看了一些排名靠前的解法,均未发现其有何时间的优越之处,很多思路类似。