Small knowledge, big challenge! This paper is participating in theEssentials for programmers”Creative activities

In golang, there is no remove operation for slice. For possible array deletions, other methods are required:

Slice’s append function

This method, which is common, uses append to concatenate the upper and lower parts of the function except for the deleted element.

The concrete implementation is also relatively simple:

s := []int{0.1.2.3.4}
index := 2    // Index of the element you want to delete
s = append(s[:index], s[index:]...)
// s => [0, 1, 3, 4]
Copy the code

The main thing to note is that… (deconstruction method), which is actually a syntactic sugar of Golang, passes slice in pieces as an argument, which is equivalent to a for traversal that dispatches all the elements in the slice. The reason for this is that the second argument to the append, the element to be added, needs to accept a mutable function. Passing it directly to slice is not recognized.

As for how to locate the table below the element you want to remove, you can search with binary lookup using sort.search() of the sort package (complexity O(logn)).

Use the container/ List package

Because array deletion requires moving elements and the complexity is high O(n), linked lists can be used to replace frequent deletion operations:

In container/ List, the list class provides a Remove function that can be removed by passing in elements as in Python.

The method of use is also relatively simple:

l.Remove(a)
Copy the code

The deletion in the linked list does not need to move the element, but only needs to connect the two pointer items before and after the deleted element, which is very low O(1).

However, its disadvantages are also obvious. In the query, elements can only be located by traversal, and the time complexity is O(n).

Therefore, linked lists are generally used in situations where the first and last elements change frequently.