Beautiful Arrangement II (M)
题目
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.
Note:
- The
n
andk
are in the range 1 <= k < n <= 10^4.
题意
对1-n这n个整数进行排列,使得到的序列相邻两个数字的差组成的集合中正好有k个不同的值。
思路
考虑这样一个问题,即给定n个整数形成一个排列,如何让相邻数字的差正好有n-1个不同的值。方法为头尾交叉插入,以 n=8 为例,依次插入 1、8、2、7、3、6、4、5,这样得到的差值分别为 7、6、5、4、3、2、1,满足条件。在此基础上解决原题:只要先找到k-1个不同的差值,剩下的数全升序或降序排列(即差值恒为1)就能满足有且仅有k个不同的差值。
代码实现
Java
class Solution {
public int[] constructArray(int n, int k) {
int[] ans = new int[n];
int left = 1, right = n;
for (int i = 0; i < n; i++) {
if (i < k) {
ans[i] = i % 2 == 0 ? left++ : right--;
} else {
ans[i] = k % 2 == 0 ? right-- : left++;
}
}
return ans;
}
}