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.
构造。很明显,如果序列是1,2,3....n会有1个不同。这里我们只要改变后面两个数字的顺序就会得到{2,1}两个不同的数。如果交换3个数比如1,2,3,4 得到 1,4,2,3 会有{3,2,1}3个不同。其实,我们只要k和i构造k-i的差值就行了,比如n = 4,k = 3 那么我们可以构造差值 3 2 1就行了。所以序列是 1 4,2,3。比如n=5,k=3我们构造差值3,2,1
所以序列是 1,4,2,3,5
O(n^2)代码。
class Solution { public: vector<int> constructArray(int n, int k) { vector<int> a(n); for (int i = 0; i < n; ++i) { a[i] = i + 1; } if (k == 1) return a; for (int i = 0; i < k - 1; ++i) { reverse(a.begin() + i + 1, a.end()); } return a; } };
O(n)代码
class Solution { public: vector<int> constructArray(int n, int k) { vector<int> ans; int l=1,r=k+1; while(l<=r) { ans.push_back(l); l++; if(l<r) ans.push_back(r--); } for(int i=k+2; i<=n; i++) ans.push_back(i); return ans; } };