优化使用复合比较器和限制条件的数组排序。

huangapple go评论69阅读模式
英文:

Optimising the sorting of the array that uses compound comparator and limit

问题

我有一个任务,需要对一个餐厅数组进行排序,有多个字段需要排序。[营业/关闭、楼号、距离、相关性]。我的问题是,为了评估距离指标,我需要向特定的 API 发送请求。我还需要尽量减少发送的请求次数。但问题在于,我只需要排好序的列表前面的10个值。这让我想到,如果例如按照营业/关闭对列表进行排序后,第一组餐厅的数量大于10,那么我就不需要为其余的餐厅评估距离,建筑号的情况也是如此。我的问题是 - 在Java中是否有一种优雅的方式来实现这一点,还是我需要自己编写代码呢?

英文:

I have a task of sorting an array of restaurants there are multiple fields they are ought to be sorted by. [open/closed,building number, distance, relevance]
My issue is that in order to evaluate the distance metric I need to send a request to the specific api. I also need to minimize the number of requests sent. But here is the caveat I only need 10 values from the top of the sorted list. And this made me think that I might not need to send the request to evaluate the distance for all of the restaurants if for example after sorting the list by open/closed the number of restaurants in the first group is larger then 10 I do not need to sort the remaining restaurant by their distance, same applies for the building number in this example.
My question is - is there a way to do this elegantly in Java, or will I have to write my own stuff.

答案1

得分: 1

首先,按照所有容易排序的字段进行排序(即您无需调用外部 API 的字段)。从最优开始。

接下来,使用一个比较器构建一个优先队列,该比较器的工作方式与您想要的完全相同,但返回最差的元素。同时,还要缓存调用 API 的结果,以便您不会为相同的元素调用两次。

将排序后的列表中的前10个放入您的队列中。

遍历您的列表的其余部分。如果它比队列中的最小元素更好,则将其添加到队列中并从队列中弹出。如果不是,则继续下一个。

完成后,您的优先队列将拥有最佳的前10个元素。它将从最差到最佳逐个提供它们给您。因此,连续弹出10次,然后反转数组以获得最终答案。

这将仅在您有充分理由相信它将出现在最终答案中,并且在此查找需要打破平局时才运行昂贵的查找。

英文:

First, sort by all of the fields that are cheap to sort by (ie you don't have to call the external API). With best first.

Next build a Priority Queue with a comparator that works exactly like you want but returns the worst element first. Have it also cache results from calling the API so that you don't call twice for the same element.

Put the first 10 of your sorted list into your queue.

Go through the rest of your list. If it is better than the minimum in your queue, add it to the queue and pop from the queue. If it isn't, then just move to the next.

Once you are done, your priority queue has the 10 best. It will give them to you from worst to best. So pop 10 times then reverse the array for your final answer.

This will run the expensive lookup only when you have good reason to believe that it will be in the final answer, and when this lookup is required to break a tie.

huangapple
  • 本文由 发表于 2020年10月8日 03:30:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/64251071.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定