Given sequence A=(a1,a2...an)
find Kth Smallest Element in iteration A[1,k],A[a,k+1]...A[1,n]
For the Input Format, the first line is n and k,
the second line is sequence A
Sample Input 0
5 2
9 8 1 2 0
Sample Output 0
9 8 2 1
Explanation:
A[1,2]=(9,8), the 2nd smallest element is 9
A[1,3]=(9,8,1), the 2nd smallest element is 8
A[1,4]=(9,8,1,2), the 2nd smallest element is 2
A[1,5]=(9,8,1,2,0), the 2nd smallest element is 1
Below is my attempt, can pass test case 0 but appears to be time out after test case 1, how can I lower time complexity
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
|
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include<climits>
using namespace std;
int main() {
int n,k,l,q=0;
cin >> n >> k;
vector<int>arr(n);
vector<int> arr2(n);
for(int j=0;j<n;j++)
cin >> arr[j];
vector<int>::iterator it;
for(int i=0;i<n-k+1;i++)
{
arr2=arr;
for(l=0;l<k-1;l++)
{
it = min_element(arr2.begin(), arr2.begin()+k+q);
*it=INT_MAX;
}
cout<<*(min_element(arr2.begin(),arr2.begin()+k+q))<<" ";
q++;
}
return 0;
}
|