簡體   English   中英

計算此方法的效率

[英]Figuring out the efficiency of this method

我在 Java 開發我的程序時遇到過。我需要弄清楚這種方法在 Big-O 表示法中的效率。

這是我的老板告訴我的:

使用合適的 Big-O 表達式 state 並詳細解釋方法計算的時間復雜度。 您的解釋必須包含所選 Big-O 表達式的理由,並參考第 6 行的計算調用次數。

 public int compute(int[] array, int first, int last) { int result = 0; if(first < last) { result = array[first] + compute(array, first+2, last); } else if(first < array.length) { result = array[first]; } return result; }

要回答此類問題,親自瀏覽代碼並查看其功能很有用。 一旦你能把這個方法用常規的詞表達出來,通常就更容易計算出效率了。

那么這個方法有什么作用呢? 它將數組中從firstlast的所有其他數字相加。 仔細檢查,我們可以將 function 分解為

  • 基本案例
    • else if (first < array.length) {... }返回索引first處的元素,或常量0 由於數組索引是恆定時間操作,因此該分支在恆定時間內執行。
    • 隱含地,如果上述兩種情況均未觸發,則result仍為 0。 這顯然是恆定時間。
  • 遞歸情況if (first < last) 在這種情況下,我們最終返回array[first]添加到使用first+2調用 function 的遞歸結果。

查看 function,我們可以看到每次迭代first都更接近last 2,直到它們接觸,此時 function 返回。

那么,這種情況會發生多少次? 答案是(last - first) / 2 如果first總是從 0 開始, last總是從數組的最后一個索引開始,那么執行次數將與array的長度成線性比例。 讓我們調用 {數組的長度} n

因此,function 執行常數O(1)次操作,並被調用 O( n ) 次。 O(1) * O(n) == O(n)

我假設您可以使用表達式運算符將所有這些縮短到大約 2-3 行。 您可以使用?:運算符確定result的值,然后返回結果。

?:被用作一種 if/else 語句,所以這就是它讓它變得更好的原因。 不過,我不確定我是否將效率與可讀性混為一談。

這是示例:

public int compute(int[] array, int first, int last) {
        int result = 0;
        
        result = first < last ? array[first] + compute(array, first+2, last) : first < array.length ? array[first] : result;
        
        return result;
    }```

暫無
暫無

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

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