我有一個TrackDay對象的列表,用於跑步者在不同的日子裏繞着田徑場奔跑。每對開始/結束時間表示跑步者單圈跑。我們保證不存在(它們出現在相應的列表的順序)匹配的開始/結束日期:找到最受歡迎的N個元素
TrackDay() {
List<DateTime> startTimes
List<DateTime> finishTimes
}
我想找到的前N天(可以說3)運動員跑最多。這轉換爲找到每個TrackDay對象N個最長的總開始/結束時間。天真的做法將做到以下幾點:
for (TrackDay td : listOftrackDays) {
// loop through each start/finish lists and find out the finish-start time for each pair.
// Add the delta times (finish-start) up for each pair of start/finish objects.
// Create a map to store the time for each TrackDay
// sort the map and get the first N entries
}
有沒有更好的,更乾淨/有效的方式來做到上述?
使用Collection.sort()和自定義比較器。 – 2015-11-05 16:25:03
我願意做Jawad說的話,並在'TrackDay'類中添加'totalTime()'方法 – phflack
@JawadLeWywadi感謝您的建議。你能否擴展一下這個比較器的工作原理,TrackDay的定義是不能改變的。一個代碼片段將極大地幫助 –