java - Algorithm Design - Fast Efficient Best Implementation -
i got question @ interview. reply below, wondering if had done better.
question: have array of names , have homecoming array sames names such name not in same position in original array.
my solution: phone call collections.shuffle shuffle array. not guarantee elements end @ different positions in original array. solve looped through array, if @ index except 0-index if name in same position original array, swap element @ index 0. , special case index 0, if same original array, swap lastly index.
this guarantees array returned not have elements in same position in original array.
do think answer? runtime o(n). or can think of improve approach?
for array of length 0 or 1, impossible. other length, next should do:
void moveelements(string[] array) { string first = array[0]; system.arraycopy(array, 1, array, 0, array.length - 1); array[array.length - 1] = first; }
java algorithm sorting design
No comments:
Post a Comment