是的,它可以在O(N)
時間完成。我會給你一個關於如何去做的方法。如果我正確理解你的問題,你需要數組的數量大於數組中所有下一個元素的數量,只要維持順序。
所以:
Let len = length of array x
{...,x[i],x[i+1]...x[len-1]}
We want the count of all elements x[i] such that x[i]> x[i+1]
and so on till x[len-1]
開始遍歷從前端,即數組在i = len -1
,並跟蹤你所遇到的最大元素。
這可能是這樣的:
max = x[len-1] //A sentinel max
//Start a loop from i = len-1 to i = 0;
if(x[i] > max)
max = x[i] //Update max as you encounter elements
//Now consider a situation when we are in the middle of the array at some i = j
{...,x[j],....x[len-1]}
//Right now we have a value of max which is the largest of elements from i=j+1 to len-1
因此,當你遇到一個x[j]
比max
大,你已經基本上發現,比旁邊的所有元素更大的元素。你可以擁有一個計數器並在發生這種情況時增加計數。
僞代碼顯示算法的流程:
counter = 0
i = length of array x - 1
max = x[i]
i = i-1
while(i>=0){
if(x[i] > max){
max = x[i] //update max
counter++ //update counter
}
i--
}
所以最終counter
將有您所需要的元素數量。
希望我能解釋你如何去做這件事。編碼這應該是一個有趣的練習作爲一個起點。
你甚至不需要輔助數組,你呢? – 2015-03-03 10:01:26
@Meehm Nope,但我覺得這種模式更容易模型化。它非常清楚你正在尋找的方式(一個元素使得'arr [i]> max {arr [i + 1],...,arr [n-1]}')。如果以後的空間成爲問題,則優化它很容易。 – amit 2015-03-03 10:02:57