有一些有趣的逻辑,我试图以最有效和最易读的方式编码。我将在下面列出一个模拟/虚拟的上下文。
我有一个银行及其出纳员评论的数据存储(1-5 int字段)。出纳员可以有一个客户选择优胜者(CCW)字段。我的要求如下所示,为一家银行向用户显示最多5名出纳员:
我必须为5家银行做上述工作。我得到的逻辑是有一个for循环来遍历5家银行,在每个循环中,对每个银行的所有出纳员进行5次检查(选择5位出纳员)。在我看来,这似乎是非常低效和不明确的。我的意思是:
foreach (Bank b : banks) {
List<Tellers> tellers = b.getTellers();
foreach (Teller t : tellers) {
List<Reviews> reviews = t.getReviews();
...// get 4 reviews following the above logic.
}
}有人能帮我用一种更清晰、更有效的方式来写这个吗?
谢谢!
发布于 2015-08-31 14:44:17
对此最好的解决方案是对列表进行排序。
您必须通过实现可比较的接口为Teller对象定义一个比较函数。
这将允许您在固定时间内运行算法(O(25),因为5家银行有5名出纳员,实际上是O(1))。
以第一次排序为代价,这将是O(nlogn)
Teller类的示例代码:
public class Teller implements Comparable
{
private boolean ccw = false;
private int rating;
public boolean hasCCW() { return ccw; }
public int getRating() { return rating; }
//... your code
@Override
public int compareTo(Object o)
{
Teller that = (Teller)o;
//if this has ccw and that doesn't, this < that
if(this.hasCCW() && !that.hasCCW())
{
return -1;
}
//else if this does not have ccw, and that does, this > that
else if(!this.hasCCW() && that.hasCCW())
{
return 1;
}
//else they both have ccw, so compare ratings
else
{
return Integer.compare(this.getRating(), that.getRating());
}
}
}然后,您的算法只需抓取每家银行的前5名出纳员。
示例:
//Sort the tellers:
//ideally, call this only once, and insert future Tellers in order (to maintain ordering)
for(Bank bank : banks)
{
for(List<Teller> tellers : bank.getTellers())
{
Collections.sort(tellers);
}
}
//then, to get your top tellers:
for(Bank bank : banks)
{
Teller bestTeller = bank.getTeller(0);
Teller secondBestTeller = bank.getTeller(1);
//...
}https://stackoverflow.com/questions/32313484
复制相似问题