find repeated number

wayneh

Joined Sep 9, 2010
17,498
IF we know and have a reasonable range on the values of the numbers (and assuming they are integers), then we can just use the number as an index to an array and increment the value at that index in a counter array.
Nice. I tried this and, no surprise, it's 3-10X faster than my sort-first approach.

I set up my test array as an arbitrary number of random elements but constrained them to integers 0-99 (details not shown belo. I used 1,000 elements for my test. Upping that to 100,000 elements widened the gap to about 20X. (And also revved the fan on my laptop!)

I'd test the other approaches if I could figure them out.

Swift:
let n = 100000
var bigA =  [UInt32](repeating: 0, count: n)
for i in 0..<n {
    bigA[i] = arc4random_uniform(100)
}
var ind = [Int](repeating: 0, count: n)
let start = Date()
for j in bigA {
    ind[j] += 1
    }
runMax = ind.max()!
winner = ind.firstIndex(of: runMax)!
elapsed = Int(Date().timeIntervalSince(star)*1000)
print("Elapsed Index = \(elapsed)")
print(winner)
print(runMax)
 
Last edited:
Top