簡體   English   中英

該方法最差的運行時間是多少?

[英]What is the worst case running time for this method?

    public String mostFrequent(){
        int a = 0; Set s = hm.keySet(); String r = ""; 
        Iterator<String> itrs = s.iterator();
        while (itrs.hasNext()){
            String b = itrs.next(); 
            if (hm.get(b) > a){ 
                a = hm.get (b);
                r = b;
            }
        }
   return r; 

我知道get(v)的最壞情況運行時間是o(n)。 那么,由於在一次while循環中兩次使用get(b),此方法的最壞情況是運行時間o(n ^ 3)嗎? 我不確定我認為正確與否。 感謝您的各種提示和解釋!

我建議您閱讀Cormen或Tamassia的幾章。 讓我們訪問您的問題陳述。

1)Hashmap上的操作必須是理想的恆定時間(盡管它們取決於負載因子),我們可以放心地假設它是恆定時間,即O(1)。

2)keySet方法通常是O(n)時間操作。

3)在while循環中,您只是在進行查找,比較和賦值,所有這些都是運行時間為O(1)的原始操作。

4)此外,在while循環中,您不應兩次使用get方法,這沒有什么意義,您可以只使用一次並將值存儲在另一個變量中。

如果所有這些論點對您都有意義,則可以放心地說運行時間為T(n)= O(n)+ c1 O(1)+ c2 O(1)+ C3 O(1)

您可以放心地降低低階項和常數,以獲得T(n)= O(n)

如果您真的想了解這些事情,可以隨時訪問我的博客

這是可視化O()的有用方法

Imagine 1000 things

If you have an outer loop of 1000 times
        doing 1000 things thats 1,000,000 things = O(N^2)

If you do 1000 loops that is O(N)

If you do 10 loops that is O(log(N))

If you don't loop that is O(1)

Multiplying or dividing O() by any constant does nothing

O() of a sequence of things is the O() of the biggest thing in the sequence

Every level of Loops multiplies O() by N

估計N = 1000時您可以做多少事,這將為您提供正確的數量級

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM