简体   繁体   中英

Sort string that express a time and take the one closest

I have an array like this:

const array = ['Monthly', 'Annually', 'Quarterly', 'Annually', 'Quarterly', 'Monthly'];

After removed the duplicates I should get an array like this:

const array = ['Monthly', 'Annually', 'Quarterly'];

Now I should get the shortest period. I have thought to associate every string with a number so transforming the array in this way:

const array = [{name:'Monthly', order:1}, {name:'Annually',order:3}, {name:'Quarterly',order:2}];

and then compute the min according the order.

Do you have some other proposal to improve the algorithm? could be improved?

One small improvement:

Removing duplicates is redundant, as it will require O(n) space, or O(nlogn) time, since it is a variant of element distinctness problem , while finding minimal value can be done in O(n) time and O(1) space.

Also, not sure what your "order" exactly is, if it is something that is calculated once at compile / pre-processing and is constant, that's fine, as long as you don't sort the list for each query

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM