Given two integers n and k, you need to construct a list which contains n different positive integers ranging from 1 to n and obeys the following requirement:
Suppose this list is [a1, a2, a3, … , an], then the list [|a1 - a2|, |a2 - a3|, |a3 - a4|, … , |an-1 - an|] has exactly k distinct integers.
If there are multiple answers, print any of them.
这道题需要细细观测,绝对值符号一定要看清楚!
然后根据题意可知,给你个数n和k,要求排列出的等差的绝对值的种类数有k个,如果答案有多种,我们只列出一个。
OK,既然不要求求出所有的排列组合,那我们就用一种方法,瞄准一个方向前进即可。试想,假如k=n-1,如何排列能让排列满足每个等差绝对值都不同呢?如果把数组劈成两半,然后把后一半倒过来,等距离插入前半段中,就是这样:1,n,2,n-1,3,n-2,你会发现数之间的差绝对值为,n-1,n-2,n-3,n-4…..,正好满足n-1个不同值的要求。
OK,如果要求k=n-2呢?不要慌,这时候只需要将前半端左移一个距离就行了,像这样:1,2,n,3,n-1,4,n-2……你可以列举n=6,n=7来证明它的正确性。
这就是其中一种解法,很清晰,很聪明,根据这种解法,我们可写出下面的代码:
class Solution {
public:
vector<int> constructArray(int n, int k) {
vector<int> res(n, 0);
int l = 1;
int r = n;
for (int i = 0; i <= (n-1-k); ++i)
res[i] = l++;
for (int i = l-1; i < res.size(); i = i+2){
res[i] = r;
if (i+1 < res.size())
res[i+1] = l;
else
break;
r--;
l++;
}
return res;
}
};