每日一道Leetcode -932. 漂亮数组【分治算法】

在这里插入图片描述
奇数在左,偶数在右

class Solution {
    
    
    Map<Integer,int[]> memo;
    public int[] beautifulArray(int N) {
    
    
        // 数组内元素:1..N
        // 分治算法
        memo = new HashMap();
        return f(N);
    }
    public int[] f(int N){
    
    
        if(memo.containsKey(N))
            return memo.get(N);
        int[] ans = new int[N];
        if(N==1){
    
    
            ans[0] = 1;
        }else{
    
    
            int t = 0;
            for(int x:f((N+1)/2))
                ans[t++] = 2*x-1;
            for(int x:f(N/2))
                ans[t++] = 2*x;
        }
        memo.put(N,ans);
        return ans;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_41041275/article/details/111661164