Offer to come, dig friends take it! I am participating in the 2022 Spring Recruit Punch card activity. Click here for details.

Spring Trick punch card day 18 chapter 21.

Study like the seedlings of spring, see its increase, day has a director; Drop out of school such as a whetstone, see its loss, loss.

There are so many activities in digging gold. This month, I decided to use GO to brush the questions every day, on the one hand, to improve the algorithm level, on the other hand, to settle the learning of GO language.

Let’s GO!

Topic describes

Given the head of a sorted list, remove all duplicate elements so that each element appears only once. Returns a sorted linked list.

The sample

Example 1:

Enter: head = [1,1,2]

Output: [1, 2]

Example 2:

Enter: head = [1,1,2,3,3]

Output: [1, 2, 3]

Tip:

The number of nodes in the linked list is in the range [0, 300]

-100 <= Node.val <= 100

The subject data ensures that the linked list is sorted in ascending order

Their thinking

This is a familiar problem, and it’s related to linked lists.

We’ve already done the problem of removing duplicate elements,

Also brush list merge problem: merge two ordered lists

With the previous ideas, it’s easy to solve this problem:

Because it is an ascending list, the current element is compared to whether the next element is equal, and if so, the next element is removed

The following is my problem solving code, I will write the key step number annotation.

AC code

/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */
func deleteDuplicates(head *ListNode) *ListNode {
    The reason not to use head directly is to avoid missing the first value in the list
    cur := head
    // Loop the value
    forcur ! =nil&& cur.Next ! =nil {
        // If the neighboring element is a duplicate element, remove the second duplicate element and replace it with the third
        if cur.Val == cur.Next.Val {
            cur.Next = cur.Next.Next
        }else {
            cur = cur.Next
        }
    }
    // Note that this returns head, not cur
    return head
}
Copy the code

The results

conclusion

As expected, brush more questions, the train of thought.

sources

Source: LeetCode

Link: leetcode-cn.com/problems/re…

Copyright belongs to the Collar buckle network. Commercial reprint please contact official authorization, non-commercial reprint please indicate the source.

The last

Thanks for reading and welcome to like, favorites,coin(attention)!!