Solution 1.
1, k+1, 2, k, 3, k-1, 4, ...
vector<int> constructArray(int n, int k) {
int l = 1, r = k+1;
vector<int> res;
while (l <= r) {
res.push_back(l++);
if (l <= r) res.push_back(r--);
}
for (int i = k+2; i <= n; i++)
res.push_back(i);
return res;
}
Solution 2.
k
1 1 2 3 4 5 6 7
2 1 2 3 4 5 6
7
3 1 2 3 4 5 6
7
4 1 2 3 4 5
7 6
5 1 2 3 4 5 6
7 6
6 1 2 3 4
7 6 5
5 1 2 3 4 5
7 6 5
vector<int> constructArray(int n, int k) {7 6 5
5 1 2 3 4 5
7 6 5
vector<int> res(n, 0);
for(int i=0; i<n; i++) res[i] = i+1;
int t = k/2, mk = k%2;
vector<int> a(n-t, 0), b(t,0);
for(int i=0; i<n-t; i++) a[i] = res[i];
for(int i=0; i<t; i++) b[i] = res[n-1-i];
int p=0, q=0;
for(int i=0; i<n; i++) {
if(q<t && i%2==mk) {res[i] = b[q]; q++; }
else {res[i] = a[p]; p++; }
}
return res;
}
No comments:
Post a Comment