LeetCode 667. Beautiful Arrangement II
阿新 • • 發佈:2017-11-26
ive 我們 leet note class push_back from multi ons
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 };
LeetCode 667. Beautiful Arrangement II