667. 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.

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.

分析

構造題,給兩個數n和k,構造一個包含1~n的數組,讓相鄰兩位的差的絕對值有k種。

     i++ j-- i++ j--  i++ i++ i++ ...
out: 1   9   2   8    3   4   5   6   7
dif:   8   7   6   5    1   1   1   1 

類似于上面的構造,最小值和最大值交叉的填入數組,到達k-1時讓差絕對值為1(遞減或遞增)。這樣做可以讓前面的差絕對值橫大于1,后面遞增只添加1個新差絕對值;因為是最大最小交叉,中間的值還是有序的,也可以實現遞增或遞減
下面給出兩種構造方法的代碼,前者后面恒遞增,后者后面可以遞增或遞減

代碼

public int[] constructArray(int n, int k) {
    int[] res = new int[n];
    for (int i = 0, l = 1, r = n; l <= r; i++)
        res[i] = k > 1 ? (k-- % 2 != 0 ? l++ : r--) : l++;  //k奇偶時的變化體現在前面部分的構造
    return res;
    
    // int[] res = new int[n];
    // int i = 1,j = n, p = 0;
    // for(; p < k; ++p){
    //     if(p % 2 == 0){
    //         res[p] = i ++;
    //     }else{
    //         res[p] = j --;
    //     }
    // }
    // int q = p;
    // for(;p < n; ++p){
    //     res[p] = q % 2 == 1 ? i++ : j--;  //k奇偶時的變化體現在后面部分的構造
    // }
    // return res;
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容