有一些有趣的逻辑,我试图以最有效和可读的方式进行编码。我将在下面列出一个scneario(使用模拟/虚拟上下文)
我有银行数据存储及其柜员评论(1-5 int field)。出纳员可以选择具有Customer Choice Winner(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.
}
}
任何人都可以用更清晰,更有效的方式帮我写这个吗?
谢谢!
答案 0 :(得分:1)
对此最好的解决方案是对List&lt; Teller&gt;
进行排序您必须通过实现Comparable接口为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);
//...
}