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

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:

  1. The n and k are in the range 1 <= k < n <= 104.

題目分析:給定n和k,要求輸出一個包含1-n的序列,序列滿足規律:相鄰數差的絕對值得種類恰好是k個。
輸出序列必然存在多個(證明:假設序列q符合題意,那麼reverse(q)必然也成立)。現在假設這k個差表示的是1到k,並且相鄰差的絕對值也是按照這個順序。構造的符合題意得數列如下:

 
k=1: 1 2 3 4 5 6 7
k=2: 2 1 3 4 5 6 7
k=3: 2 3 1 4 5 6 7
k=4: 3 2 4 1 5 6 7
k=5: 3 4 2 5 1 6 7
……..

規律:
1、p[0]=k/2+1;
2、deta=1到k,正負號相間
3、若k是奇數,則deta先正後負,否則先負後正。
7、以上規律持續到deta=k,即第(k+1)個位置,之後的數據順序遞增。

代碼如下:

class Solution {
    public int[] constructArray(int n, int k) {
        int[]result=new int[n];
        int st=(k/2)+1;
        boolean flag=k%2==0?false:true;
        result[0]=st;
        for(int i=1;i<=k;i++){
            if(flag)
                result[i]=result[i-1]+i;
            else
                result[i]=result[i-1]-i;
            flag=!flag;
        }
        for(int i=k+1;i<n;i++)
            result[i]=i+1;
        return result;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章