Answer the question
In order to leave comments, you need to log in
Variable vs loop in this case?
There is, for example, an array of 10 cells.
In certain cases, you need to find out if there is a certain number in this array (any cell).
Solution 1: Loop checking all cells for digit content.
Solution 2: Along with setting a digit in an array cell, create a variable to which we assign the index of the cell containing this digit.
But when deleting a digit from the array, you will also have to clear the variable containing the index of this digit in the array.
Answer the question
In order to leave comments, you need to log in
Certainly a cycle. What will you do when you need to know the presence of two specific digits?
Depends on the statistics of hits.
If checks go much more often than array changes, then a variable. Moreover, when "deleting" a digit, you will have to not only clear the cell, but go through the entire array - is there another such digit there.
If checks and changes go in series (many changes - many checks), then two variables. In one - an index, in the other a sign of whether it has deteriorated. Then, when checking with a "corrupted" index, you will have to go through the array and see where the number is now. Although you can simply check what is now in the cell with the index. If not the desired digit - a new pass through the array. But here it is already necessary to look at which cell deteriorates most often - the one in which the digit appeared the earliest, or the one where it appeared the latest.
If checks are infrequent enough,
In difficult cases - when the array contains not 10, but 1000 cells, there can be a lot of numbers, they change often, and you need to often check if there is a number, and where exactly - you will need to store cell indices with these numbers in some structure. For example, in a doubly linked list built on two arrays parallel to the working one. Then all changes and checks will work for O(1).
In general, it all depends on the situation.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question