我认为您的解决方案还可以,但要正常工作,它应该类似于:
a[n]//the array
minimum[n-l+1]//fixed
minpos=position_minimum_in_subarray(a,0,l-1);
minimum[0]=a[minpos];
for(i=1;i<=n-l-1;i++)
{
if(minpos=i-1)
minpos=position_minimum_in_subarray(a,i,i+l-1);
else if(a[minpos]>a[i+l-1]) //fixed
minpos=i+l-1; //fixed
minimum[i] = a[minpos];
}
// Complexity Analysis :
//Time - O(n^2) in worse case(array is sorted) we will run
"position_minimum_in_subarray" on each iteration
//Space - O(1) - "minimum array" is required for store the result
如果你想提高你的时间复杂度,你可以用额外的空间来做。例如,您可以将每个子数组存储在一些自平衡 BST(例如红黑树)中,并在每次迭代时获取最小值:
for (int i= 0; i<n; i++) {
bst.add(a[i]);
if (bst.length == l) {
minimum[i-l] = bst.min;
bst.remove(a[i - l]);
}
}
//It's still not O(n) but close.
//Complexity Analysis :
//Time - O(n*log(l)) = O(n*log(n)) - insert/remove in self-balancing tree
is proportional to the height of tree (log)
//Space - O(l) = O(n)