LeetCode Collection (59) - 83 title Remove Duplicates from sorted list

problem

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

复制代码

translation:

Given a sorted list, remove all duplicate entries, so that each element occurs only once. Example 1: Input: 1 -> 1 -> Output 2: 1 -> 2 Example 2: Input: 1 -> 1 -> 2 -> 3 -> Output 3: 1 -> 2 -> 3


Problem-solving ideas

This idea is very simple question, because the list is ordered, indicating if there are duplicate, certainly the next, traversing the order, the same as a node after the current node and if they are, then cover the current node. Traversal time to get

Problem-solving approach

  1. According to our idea to edit the code as follows

    public ListNode deleteDuplicates(ListNode head) {
    
        if (head == null) {
            return head;
        }
    
        ListNode temp = head;
        while (head.next != null) {
            if (head.val == head.next.val) {
                head.next = head.next.next;
                continue;
            }
            head = head.next;
        }
        return temp;
    
    }
    
    public class ListNode {
        int val;
        ListNode next;
    
        ListNode(int x) {
            val = x;
        }
    }
    复制代码

    Time Complexity : The program cycle with m so f (n) = (n) = n; so O (f (n)) = O (n), i.e., T (n) = O (n )

    Space complexity : The program uses the extra space is not used, so the space complexity is O (n) = O (1 );

to sum up

Solution of this problem is substantially above v, solving this problem is substantially only one way to directly read cover traversed, I by comparing the current node and the next node, and may be compared before a node.

Reproduced in: https: //juejin.im/post/5cfa8a846fb9a07ea803bc61

Guess you like

Origin blog.csdn.net/weixin_33897722/article/details/91456314