leetcode- Beautiful Arrangement II

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 and k are in the range 1<=kn<=104 .

思路:假设每一次 k = n-1

nk满足条件的序列
211 2
321 3 2
431 4 2 3
541 5 2 4 3
651 6 2 5 3 4

通过以上可以看出当 k=n-1 时,满足条件的序列都满足 min – max – min+1 – max-1 – min+1+1 – max-1-1 …

因此对于给出的任意 1<=kn<=104 可以先找出 m = k+1 时满足的序列,然后对于 [m+1, k] 之间的序列,只需按序存到数组中,相邻两个数据的差都为1

class Solution {
    public int[] constructArray(int n, int k) {

        int tail = k+1;
        int front = 1;
        int[] ans = new int[n];
        for(int i = 0; i <= k; i++){
            if(i%2 == 0){
                ans[i] = front++;
            }else{
                ans[i] = tail--;
            }
        }

        for(int i = k+2; i <= n; i++){
            ans[i-1] = i;
        }
        return ans;
    }
}
点赞