LeetCode: 932. Beautiful Array 完美序列满足A[k] * 2 = A[i] + A[j]

试题
For some fixed N, an array A is beautiful if it is a permutation of the integers 1, 2, …, N, such that:

For every i < j, there is no k with i < k < j such that A[k] * 2 = A[i] + A[j].

Given N, return any beautiful array A. (It is guaranteed that one exists.)

Example 1:

Input: 4
Output: [2,1,4,3]
Example 2:

Input: 5
Output: [3,1,2,5,4]

代码
分治思想;

class Solution {
    Map<Integer, int[]> memo;
    public int[] beautifulArray(int N) {
        memo = new HashMap();
        return f(N);
    }
    
    //完美序列可以通过映射得到新的完美序列:
    //2*(a[k] + x) != (a[i] + x) + (a[j] + x) ,当序列中元素加上x时,新的序列仍然满足完美序列
    //2*(a[k]*y) != a[i]*y + a[j]*y ,当序列中元素乘以y时,新的序列仍然满足完美序列
    public int[] f(int N){
        if(memo.containsKey(N)) return memo.get(N);
        
        int[] tmp = new int[N];
        if(N == 1){
            tmp[0] = 1;    //最简单的完美序列N=1时的[1]
        }else{
            int t = 0;
            //1、假设f((N+1)/2)是完美序列,那么对其乘2减1后仍然是完美序列,
            for(int x : f((N+1)/2))   //对于1~N,有(N+1)/2个奇数,使用1~(N+1)/2映射到1-N中奇数
                tmp[t++] = 2 * x - 1;
            //2、假设f(N/2)是完美序列,那么对其乘2后仍然是完美序列
            for(int x : f(N/2))       //对于1-N,有N/2个偶数,使用2N映射到1-N中偶数
                tmp[t++] = 2 * x;
            //3、当将奇数和偶数拼接起来后,因为奇数部分和偶数部分已经满足,那么只需要考虑奇偶合并起来的情况,当i在奇数部分而j在偶数部分时显然a[i](奇数) + a[j](偶数) != a[k](偶数)。所以拼接起来的序列仍然是完美序列。
            
        }
        memo.put(N, tmp);
        return tmp;
    }
}
发布了557 篇原创文章 · 获赞 500 · 访问量 153万+

猜你喜欢

转载自blog.csdn.net/qq_16234613/article/details/100920627