[Data structure and algorithm] Use the sequence table to delete all data elements whose value is item in the linear table

foreword

In the linear table chapter of learning data structures and algorithms, a homework about the deletion operation of linear tables is assigned. I feel that the main difficulty is to control its space complexity and time complexity, and it is easy to exceed the limit given by the title. Not much nonsense, let's take a look at the topic below.


topics and requirements

It is known that the linear table A with a length of n adopts a sequential storage structure. Please write an algorithm with a time complexity of O(n) and a space complexity of O(1) . This algorithm deletes all data elements whose value is item in the linear table .


pit encountered

  1. At first glance, it seems quite simple, isn't it just to find the value of item, and then delete it, so I used the while loop + LocateElem + ListDelet to get it right? Then think about it carefully, this time complexity far exceeds the level of O(n), reaching O(n*n*n), so this idea was directly passed.

This code is missing a return 0, so I didn't pay much attention at the time

  1. Later, I thought of traversing the linear table first, taking out all the items that match the item value, and storing them in an array. The array stores the subscript of the element to be deleted, and then use delete to delete the data element of the fixed position. , Then I turned my head and thought about it and felt wrong. Here, the subscript is stored in the array. When deleting, the time complexity may exceed O(n), so this solution is also given up.


Solution and code

I think it may be more appropriate to use double pointers to solve this problem later. Of course, there are better solutions. As a beginner, I use the double pointer method to solve this problem.

The first code:

//第一种方案代码
Status deleteElem(List &L, ElemType item){
    int slow = 0, fast = 0;
    int cnt = 0;
    for(  ;fast < n; ++fast)
    {
        if(L.data[fast] == item) { ++cnt; continue; }
        L.data[slow] = L.data[fast];
        ++slow;
    }
    if(!cnt)  return error;
    L.length = cnt;
    return ok;
}

The second code:

Illustration of the second code:


conclusion

Because it is an algorithm side dish, the methods and ideas provided may not be very good, please bear with me~ If you have any questions, please leave a message to discuss. If you think this article is helpful to you, can you give me a free like? The communication between us is my biggest motivation!

Guess you like

Origin blog.csdn.net/Zchengjisihan/article/details/129625584