22 - 删除排序链表中的重复元素
题目
给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
示例 1:
输入: 1->1->2 输出: 1->2
示例 2:
输入: 1->1->2->3->3 输出: 1->2->3
解答
直观解法
看一下next
指向的val
是不是和当前的相等,相当就指向next
的next
。
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var deleteDuplicates = function(head) {
let cur = head
while(cur && cur.next) {
if(cur.val === cur.next.val) {
cur.next = cur.next.next
} else {
cur = cur.next
}
}
return head
};
Runtime: 64 ms, faster than 85.11% of JavaScript online submissions forRemove Duplicates from Sorted List.
Memory Usage: 36.1 MB, less than 25.00% of JavaScript online submissions for Remove Duplicates from Sorted List.
Last updated
Was this helpful?