I dont know how doint that. I try find replacement obj method
indexOfObject on the swift but not find
i have array = [1,3,6,2,3] and input in array value 3, i am need find repeating value with min index from array. Answer with index 1. How do it?
I dont know how doint that. I try find replacement obj method
indexOfObject on the swift but not find
i have array = [1,3,6,2,3] and input in array value 3, i am need find repeating value with min index from array. Answer with index 1. How do it?
3
Answers
Assume you have an array of n integers, with a[i] = i, except that a[1] = a[2] = 1, and I may or may not have have changed a[i] = 0 for some i >= 2.
The smallest index of a duplicate element is either 0 or 1. To find out which you have to find the i >= 2 with a[i] = 0 or find that no such i exists. So you have to visit all array elements.
You have to loop through the entire collection, for each item, see if we had seen this before. And as we are doing that, let’s keep track of the index of the first item that has been repeated somewhere in the collection, to see if this is the first repeated item or not:
Thus:
Now, obviously, as we iterate through this array, the value
3
is the first value that we will see repeated, but that doesn’t matter, because the repeated value1
will be found at the very end of the array, and1
’s first index is lower than3
’s first index.Two observations on the above:
I made it generic, so that it works on any hashable type, e.g.:
I made this a
Collection
extension (rather than anArray
extension) so that it would work on other collection types (e.g. array slices, etc.). You can make it anArray
extension, just as easily, but we prefer to use the most abstract type that is convenient, to make it as flexible as possible.This is basically a riff on
uniqued
.You can get the last duplicate by not reversing before reducing.