[leetcode]667. Beautiful Arrangement II
Analysis
ummmmm~—— [ummmm]
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.
ummmm 算是个找规律的题目了吧~
Implement
class Solution {
public:
vector<int> constructArray(int n, int k) {
vector<int> res;
int num1 = 1;
int num2 = n;
for(int i=0; i<k; i++){
if(i%2 == 0)
res.push_back(num1++);
else
res.push_back(num2--);
}
if(k%2 == 1){
for(int i=num1; i<=num2; i++)
res.push_back(i);
}
else{
for(int i=num2; i>=num1; i--)
res.push_back(i);
}
return res;
}
};