Given an array of size N in which every number is between 1 and N, determine if there are any duplicates in it. You are allowed to destroy the array if you like.
Set two n-bit bitmaps, N1 and N2, each bit is for each value of array
Scan the array, for each value v, if vth position of N1 is o, set vth position of N1, else if vth position of N2 is o, set vth position of N2, else do nothing.
After scan, N1 AND N2, the positions with 1s are duplicate value
if we only want to check whether there is a duplicate in the array, compare the sum of array to (N+1)*N/2. This way does not work…
1,2,3,4 and 1,1,4,4
Use all msb of array as bitvector, if the msb is set, which means this number is duplicate, or just set the msb
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment