是的,它可以在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