1. Description
Given two integers n and k. Construct a list which contains 1 to n and the diffs between the neighbor elements has exactly k distinct integers.
2. Solution
Use two points to traverse the array.
Pick one element from the most left, and then pick one element from the most right.
Then there will be two different diff( the diff between the second element and the first element, and the diff between the coming element and the second element).
Repeat this process, until form k or k-1 different diffs.
If there are 1 left diff needed to form, pick the left numbers from min to max.
If the k diffs have been formed, pick the left numbers from max to min.
3. Code
vector<int> constructArray(int n, int k) {
vector<int> ans;
int i=1,j=n;
for(;i<j&&k>1;i++,j--){
ans.push_back(i);
ans.push_back(j);
k=k-2;
}
if(k==1){
for(;i<=j;i++)
ans.push_back(i);
}
else{
for(;i<=j;j--)
ans.push_back(j);
}
return ans;
}