83. Remove Duplicates from Sorted List

Leetcode

https://leetcode.com/problems/remove-duplicates-from-sorted-list/

題目

Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.

Example 1:

Input: head = [1,1,2]
Output: [1,2]

Example 2:

Input: head = [1,1,2,3,3]
Output: [1,2,3]

解答

  • 方法一

var deleteDuplicates = function(head) {
    let start = head;
    while(head && head.next) {
        if(head.next.val === head.val) {
            head.next = head.next.next
        } else {
            head = head.next;
        }
    }
    return start;
};

Runtime: 108 ms, faster than 31.97% of JavaScript online submissions for Remove Duplicates from Sorted List.

Memory Usage: 40.7 MB, less than 65.44% of JavaScript online submissions for Remove Duplicates from Sorted List.

Last updated

Was this helpful?