Ich habe versucht, diese Probleme auf SPOJ zu lösen http://spoj.pl/problems/ARRAYSUBSPOJ ARRAYSUB: O (n) Komplexität Ansatz
ich gelöst es zwei Ansätze
zunächst optimierte Brute-Force mit. Zweitens, Pivot bei k, 2k, 3k usw. nehmen und Maximum finden.
Obwohl beide Lösungen im ungünstigsten Fall akzeptiert werden, ist die Komplexität O (n * k);
Kann jemand vorschlagen, O (n) -Lösung Ansatz für die Probleme.
Unten ist mein Laufcode von Worst-Case-Komplexität O (n * k) angenommen:
#include<iostream>
#include<cstdio>
#include<climits>
using namespace std;
main()
{
long n;
cin >> n;
long *arr = new long[n];
for(long i=0;i<n;i++)
cin >> arr[i];
long k;
cin >> k;
long max=arr[0];
for(long i=1;i<k;i++)
{
if(arr[i]>max)
max=arr[i];
}
if(k!=n)
cout<<max<<" ";
else cout<<max;
for(long i=k;i<n;i++)
{
if(arr[i-k]==max)
{max=-1;
for(int j=i-k+1;j<=i;j++)
if(arr[j]>max)
max=arr[j];
if(i!=n)
cout<<max<<" ";
else cout<<max;
}
else{
if(arr[i]>max)
{ max=arr[i];
if(i!=n)
cout<<max<<" ";
else
cout<<max;
}
else
{
if(i!=n)
cout<<max<<" ";
else cout<<max;}
}
}
cout<<endl;
return(0);
}
@ sajalijain4 bitte erklären Sie den Algorithmus deutlicher? Ich meine nicht, Coder von dir zu bekommen. Mein Moto war, den Ansatz zu kennen. Bitte erläutern Sie es im Detail. danke im voraus –
Ich habe eine Erklärung hinzugefügt. Bitte sagen Sie mir, wenn es verständlich ist –
Ist dieser Artikel auch Ihre Arbeit? Der Code dort ist fast identisch. http://articles.leetcode.com/sliding-window-maximum/ – Alan