题目
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.
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.
分析
构造题,给两个数n和k,构造一个包含1~n的数组,让相邻两位的差的绝对值有k种。
i++ j-- i++ j-- i++ i++ i++ ...
out: 1 9 2 8 3 4 5 6 7
dif: 8 7 6 5 1 1 1 1
类似于上面的构造,最小值和最大值交叉的填入数组,到达k-1时让差绝对值为1(递减或递增)。这样做可以让前面的差绝对值横大于1,后面递增只添加1个新差绝对值;因为是最大最小交叉,中间的值还是有序的,也可以实现递增或递减
下面给出两种构造方法的代码,前者后面恒递增,后者后面可以递增或递减
代码
public int[] constructArray(int n, int k) {
int[] res = new int[n];
for (int i = 0, l = 1, r = n; l <= r; i++)
res[i] = k > 1 ? (k-- % 2 != 0 ? l++ : r--) : l++; //k奇偶时的变化体现在前面部分的构造
return res;
// int[] res = new int[n];
// int i = 1,j = n, p = 0;
// for(; p < k; ++p){
// if(p % 2 == 0){
// res[p] = i ++;
// }else{
// res[p] = j --;
// }
// }
// int q = p;
// for(;p < n; ++p){
// res[p] = q % 2 == 1 ? i++ : j--; //k奇偶时的变化体现在后面部分的构造
// }
// return res;
}
网友评论