667. Beautiful Arrangement II(python+cpp)
題目:
Given two integers
n
andk
, you need to construct a list which containsn
different positive integers ranging from1
ton
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 exactlyk
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 and k are in the range 1 <= k < n <= 104.
解釋:
這系列題目的第一題:
526. Beautiful Arrangement(python+cpp)
對於本題目,就是求1-n構成的陣列的一個序,這個序要滿足兩兩之間元素差的絕對值(相同的值算一種情況)構成的陣列大小為k。返回滿足條件的陣列序列。
嘗試著去找規律,發現是很簡單的一個規律題。首先我們確定的一點:元素差最多的個數是n-1
個,這個n-1
的構成也很容易發現,較大的數和較小的數交替形成的序列就滿足要求。例如,我們假設n= 6,k = 5,那麼這個序列就是 6 1 5 2 4 3 形成的k個元素差為: 5 4 3 2 1 (反向也是可以的 即 1 6 2 5 3 4)若k不等於n-1,我們只需要按上述規律形成滿足k-1的序列,剩餘序列按遞減序即可(剩餘的差值都為1)
假設n = 6,k = 4,我們得到的序列即是: 1 6 2 5 4 3。
所以要用雙指標做。
注意,上面的迴圈完成以後,只有k-2個,所以最後需要先往上跳一個變成k-1個,再遞減序列。上面的判斷一定是left所指的數結尾。
python程式碼:
class Solution(object):
def constructArray(self, n, k):
"""
:type n: int
:type k: int
:rtype: List[int]
"""
left=1
right=n
result=[]
while left<=right:
if k>1:
if k%2==0:
result.append(left)
left+=1
else:
result.append(right)
right-=1
k-=1
else:
result.append(right)
right-=1
return result
c++程式碼:
class Solution {
public:
vector<int> constructArray(int n, int k) {
int left=1,right=n;
vector<int> result;
while (left<=right)
{
if (k>1)
result.push_back((k--%2)==0?left++:right--);
else
result.push_back(right--);
}
return result;
}
};
總結:
c++程式碼比python程式碼更加簡潔,恩。