leetcode 932. Beautiful Array

Divide and conquer

I'm not so good at this kind of problem, so I just checked the solution page.

class Solution {
    public int[] beautifulArray(int N) {
        if (N == 1) return new int[]{1};
        else if (N == 2) return new int[]{1, 2};
        int[] odd = beautifulArray((N + 1) / 2);
        int[] even = beautifulArray(N / 2);
        int[] ret = new int[N];
        int idx = 0;
        for (int val: odd) {
            ret[idx++] = 2 * val - 1;
        }
        for (int val: even) {
            ret[idx++] = 2 * val;
        }
        return ret;
    }
}

猜你喜欢

转载自www.cnblogs.com/exhausttolive/p/10612536.html