简体   繁体   English

排序表示时间的字符串,并取最接近的时间

[英]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. 删除重复项是多余的,因为这将需要O(n)空间或O(nlogn)时间,因为这是元素差异问题的一种变体,而找到最小值可以在O(n)时间和O(1)空间。

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 另外,不确定您的“顺序”到底是什么,如果它是在编译/预处理时计算一次并且是常数的,那很好,只要您不对每个查询的列表进行排序

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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