Programming

Leetcode-83. Remove Duplicates from Sorted List

Leetcode-83. 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]

<解題>

1.


class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        ListNode current_node = head;
        while (current_node!=null && current_node.next != null){
            if(current_node.val == current_node.next.val){
                current_node.next = current_node.next.next;
            } else{
                current_node = current_node.next;
            }
        }
        return head;
    }
}

Time: O(n) Space: O(1)

2.利用遞迴


class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if(head == null || head.next == null)return head;
        head.next = deleteDuplicates(head.next);
        return head.val == head.next.val ? head.next : head;
}
}

Time: O(n) Space: O(n)

刪除重複的節點(但不會留下重複的數字的一個)

Leetcode-82. Remove Duplicates from Sorted List II