Description
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.
Example 1
Input: n = 3, k = 1
Output: [1, 2, 3]
Explanation: The [1, 2, 3] has three different positive integers ranging from 1 to 3, and the [1, 1] has exactly 1 distinct integer: 1.
Example 2
Input: n = 3, k = 2
Output: [1, 3, 2]
Explanation: The [1, 3, 2] has three different positive integers ranging from 1 to 3, and the [2, 1] has exactly 2 distinct integers: 1 and 2.
Solution 1(C++)
class Solution {
public:
vector<int> constructArray(int n, int k) {
vector<int> res(1,1);
int flag=0, dif=k, temp;
while(res.size()<n){
temp=res[res.size()-1];
if(dif>=1){
if(0==flag) {res.push_back(temp+dif); flag=1;}
else {res.push_back(temp-dif); flag=0;}
dif--;
}
else{
res.push_back(res.size()+1);
}
}
return res;
}
};
Solution 2(C++)
class Solution {
public:
vector<int> constructArray(int n, int k) {
vector<int> res;
int i = 1, j = n;
while (i <= j) {
if (k > 1) res.push_back(k-- % 2 ? i++ : j--);
else res.push_back(i++);
}
return res;
}
};
算法分析
1~n个数,任意两个数最小的差为1,最大的差为n-1,题目要求差有k个不同,这k个不同的差值,最小也为1,最大也为n-·1。题目要求给出一种可能的方法即可,所以,尝试差值为1,2,3,…,k-1.那么数列:1,k,2,2,k-1,…直到前后两个数差值为1.这个数列的个数为k,那么比n个数少的,直接在后面补齐即可。
此外,要注意,插值从k-1降到1,这是前面的数列构成,后面的额外补充的数列,添加res.size()+1。即可。这也是一个小技巧。
程序分析
略。