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.
这道题非常巧妙,考虑的是数字排列的 问题。如果暴力搜索,复杂度是O(n*n!),必然会超时,因此需要另辟蹊径,题目要求1-n之间的n个数,按照某个顺序形成了一个排列,相邻两个数做差取绝对值,形成一个新的向量,新的向量中只能有k个不同的数字,求n个数的组合。我们不难发现,k最大取值为n-1
我们其实可以反过来考虑,构造1,2,...,k+1序列,恰好可以使得差值有1,2,...,k个不同数字
1,k+1,2,k,.....
这时如果数字还没用完,那么从k+2开始遍历到n,相邻数字之间的差值均为1,不产生新的差值,满足题目要求
代码如下:
1 class Solution { 2 public: 3 vector<int> constructArray(int n, int k) { 4 int l = 1, r = k+1; 5 vector<int> ans; 6 while (l <= r) { 7 ans.push_back(l++); 8 if (l <= r) ans.push_back(r--); 9 } 10 for (int i = k+2; i <= n; i++) 11 ans.push_back(i); 12 return ans; 13 } 14 };