算法1
分析:前面一段数字先让其符合相邻数字绝对值差为k,k - 1 .....1,后面一段直接逐个+1即可。
举个例子就容易理解了:
输入:50 30
输出:[1,31,2,30,3,29,4,28,5,27,6,26,7,25,8,24,9,23,10,22,11,21,12,20,13,19,14,18,15,17,16,(前一段)
32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50](后面一段)
时间复杂度 O(n)
C++ 代码
class Solution {
public:
vector<int> constructArray(int n, int k) {
vector<int>ans;
for(int i = 1; i <= k + 2 - i; ++i){
ans.push_back(i);
if(i < k + 2 - i)ans.push_back(k + 2 - i);
}
for(int i = ans.size() + 1;i <= n;++i)
ans.push_back(i);
return ans;
}
};