leetcode-667-Beautiful-Arrangement-II

描述


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:

1
2
3
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:

1
2
3
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:

  1. The n and k are in the range $1 <= k < n <= 10^4$.

分析


1…n 这样的序列,能组成的最大的差值为 n-1, n-2, … 1, 0, 因为 $1 <= k < n <= 10^4$,所以结果肯定是存在的,只是我们需要构造一个这样的序列。根据 k 的值依次写入最大,最小值,每次写入后 k 自减1,当 k 等于1时,按照升序取剩余的数即可。

n = 3, k = 2

3, 1, 2

n = 3, k = 1
1, 2, 3

解决方案1(Java)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public int[] constructArray(int n, int k) {
int[] result = new int[n];
int count = 0;
int left = 1, right = n;
while (left <= right) {
if (k > 1) {
result[count++] = k-- % 2 == 1? left++ : right--;
} else {
result[count++] = left++;
}
}
return result;
}
}

相关问题


(M) Beautiful Arrangement

题目来源