17,610
社区成员




给你两个整数 n 和 k ,请你构造一个答案列表 answer ,该列表应当包含从 1 到 n 的 n 个不同正整数,并同时满足下述条件:
假设该列表是 answer = [a1, a2, a3, ... , an] ,那么列表 [|a1 - a2|, |a2 - a3|, |a3 - a4|, ... , |an-1 - an|] 中应该有且仅有 k 个不同整数。
返回列表 answer 。如果存在多种答案,只需返回其中 任意一种 。
class Solution {
public int[] constructArray(int n, int k) {
int i,index=1;
k-=1;
for(i=n;i>n/2+1&&k>0;i--){
if(i>index+1){
if(i-index<=2) k-=1;
else k-=2;
}
index++;
}
if(k<0){
i++;
index--;
}
List<Integer> list = new ArrayList<Integer>();
for(int j=1;j<index;j++){
list.add(j);
list.add(n-j+1);
}
if(k<0){
int j;
for(j=index;j<=n-index-1;j++){
list.add(j);
}
list.add(j+1);
list.add(j);
}else{
for(int j=index;j<=n-index+1;j++){
list.add(j);
}
}
return list.stream().mapToInt(Integer::intValue).toArray();
}
}