big o - intersection algorithm O(n) better way? -
let s1 , s2 2 sets of integers, such |s1| = |s2| = n.
all integers obtained domain [1, 20n]. give algorithm report integers in s1 ∩ s2 in o(n) worst-case time.
i'm confused, why have given me domain? know count sort both lists in o(n) + o(n) time, , use 2 pointer method compare elements in o(n) time.
i feel if i'm missing or there better way?
your way works, here way feel little less complicated sorting , iterating. follows idea of count sorting, or radix sorting, slight twist.
- create array of size 20n.
- iterate through first , second set , increment each index match value on in array created.
- iterate through array created , print out indices value of 2 in them.
this o(n).
Comments
Post a Comment