Leetcode - 667 Beautiful Arrangement II (Medium)
题目描述:数组元素的取值范围为[1, n],构建新的数组,使得相邻元素差值不相同的个数为 k。
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 为 9,k 为 8 时,可以构建数组,数组长度为 n 时,k 的最大值为 n - 1。
i: 1 2 3 4 5
j: 9 8 7 6
out: 1 9 2 8 3 7 4 6 5
dif: 8 7 6 5 4 3 2 1
当 k 为 5 时,可以构造:
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
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++;
return res;
}