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 <= 104
题目含义:给定整数n和k,列表[a1, a2, a3, ... , an] = [1, 2, 3, ..., n],重新排列,使得列表[|a1 - a2|, |a2 - a3|, |a3 - a4|, ... , |an-1 - an|] 恰好包含k个不同整数。
思路:
给定n那么k最大为n-1,假设这k个数字是 n-1,n-2,n-3...1,所以数列可以是1,n-1,2,n-2,....,
比如给定n=9 k=8则数列可以是9 1 8 2 7 3 6 4 5,可以看出这组数据差值是8 7 6 5 4 3 2 1
比如给定n=9 k=4则数列可以是9 1 8 2 3 7 4 6 5,可以看出这组数据差值是8 7 6 1 1 1 1 1
1 public int[] constructArray(int n, int k) { 2 int[] res = new int[n]; 3 int left = 1, right = n; 4 for (int i = 0; left <= right; i++) { 5 res[i] = k > 1 ? (k-- % 2 == 0 ? right-- : left++) : left++; //从最大和最小数轮流取值.k为偶数时从右拿,k为奇数时候从左拿 6 } 7 return res; 8 }