I need to find duplicates by rounded coordinates and store the indices, then remove elements from the original array by these indices. How can I do this with O(n) ?
func removeDuplicate(from points: [Point]) -> [Point] {
var originalPoints: [Point] = points
let tempRoundedPoints: [Point] = roundingCoordinates(for: points)
guard tempRoundedPoints.count > 2 else { return originalPoints }
var removableIndexes: [Int] = []
for i in 0..<tempRoundedPoints.count - 2 {
for j in i + 1..<tempRoundedPoints.count - 1 {
if (tempRoundedPoints[i]?.lat == tempRoundedPoints[j]?.lat) && (tempRoundedPoints[i]?.lng == tempRoundedPoints[j]?.lng) {
removableIndexes.append(i)
break
}
}
}
removeWith(indexes: removableIndexes, from: &originalPoints)
return originalPoints
}
2
Answers
This is a generic function to get the indices of duplicates in an array. It requires that the array element conforms to
Equatable
andHashable
. It uses aSet
to store the duplicate values and returns anIndexSet
.contains
called on aSet
is much faster than called on anArray
.Call the function on the array
To remove the items in an array at indexes in an
IndexSet
efficiently see removeObjectsAtIndexes for Swift arraysAnother problem is that identical
Double
values are not equal due to the imprecise nature of floating point representation. You could use this extension found in this questionHere’s for reference:
ps. you can post in .playground and try it, hope the answer will help 🙂
I think the time complexity is O(n log(n)) + O(n)