鑑於「線程」,其中包含2個變量的列表內共通點 - 開始時間和結束時間 - 實施將在一定時間t返回所有正在運行的線程的功能。優化它。 找到不同的時間間隔
我的解決辦法是通過列表迭代(比O(n)的更快) - 這是O(n)。有人知道如何在這裏比O(n)更快地實現嗎?
class MyThread{
Thread thread;
long start;
long end;
}//the object in the list
//function to find "threads"
public List<Thread> matchingInterval(List<MyThread> list) {
List<Thread> found = new ArrayList<Thread>();
Set<Thread> runningThreads = Thread.getAllStackTraces().keySet();
long instant = System.currentTimeMillis();
for(MyThread el: list)
if(el.start <= instant && el.end >= instant && runningThreads.contains(el.thread))
found.add(el.thread);
return found;
}
編輯:
目標是return all running threads at some time t.
我的解決方案假定time t
是時間(加/減錯誤)當我的函數被調用,因此我的long instant = System.currentTimeMillis();
有沒有可能是調用者指定一些任意時間?如果是,那麼我發現這個問題與線程本身毫無關係,所以我不需要抓取實際的runningThreads
。
還有一點:僅僅因爲一個線程是活的,它是運行?
那麼,你必須檢查每一個線程,看看它的運行,即O(N)。如果列表根據開始時間進行了預先排序,唯一的方法可能會更快一些。然後你可以對開始時間大於等於時間t的線程進行二分查找。 – noMAD 2012-04-17 17:25:42
關於正在排序的列表沒有任何說法。 – kasavbere 2012-04-17 17:44:15
我想過預先對列表進行一次排序,然後攤銷成本:由於列表是預先排序的,因此以後所有對該函數的調用都會查找預先排序的列表,並使用二分搜索,成本O(2 * LG N)是O(LG N) – kasavbere 2012-04-17 17:49:15