問題:ui
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.this
If there are multiple answers, print any of them.spa
Example 1:code
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:three
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:ip
n
and k
are in the range 1 <= k < n <= 104.解決:rem
【題意】給定整數n和k,列表[a1, a2, a3, ... , an] = [1, 2, 3, ..., n],從新排列,使得列表[|a1 - a2|, |a2 - a3|, |a3 - a4|, ... , |an-1 - an|] 剛好包含k個不一樣整數。it
① io
元素差最多的個數是n-1個,這個n-1的構成也很容易發現,較大的數和較小的數交替造成的序列就知足要求。class
例如,咱們假設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。
class Solution { //7ms public int[] constructArray(int n, int k) { int[] res = new int[n]; int left = 1; int right = n; for (int i = 0;left <= right;i ++){ res[i] = k > 1 ? (k -- % 2 == 0 ? right -- : left ++) : left ++;//從最大和最小數輪流取值 } return res; } }