All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g0901_1000.s0932_beautiful_array.Solution Maven / Gradle / Ivy

There is a newer version: 1.38
Show newest version
package g0901_1000.s0932_beautiful_array;

// #Medium #Array #Math #Divide_and_Conquer #2022_03_30_Time_1_ms_(89.66%)_Space_43_MB_(38.97%)

import java.util.HashMap;
import java.util.Map;

/**
 * 932 - Beautiful Array\.
 *
 * Medium
 *
 * An array `nums` of length `n` is **beautiful** if:
 *
 * *   `nums` is a permutation of the integers in the range `[1, n]`.
 * *   For every `0 <= i < j < n`, there is no index `k` with `i < k < j` where `2 * nums[k] == nums[i] + nums[j]`.
 *
 * Given the integer `n`, return _any **beautiful** array_ `nums` _of length_ `n`. There will be at least one valid answer for the given `n`.
 *
 * **Example 1:**
 *
 * **Input:** n = 4
 *
 * **Output:** [2,1,4,3]
 *
 * **Example 2:**
 *
 * **Input:** n = 5
 *
 * **Output:** [3,1,2,5,4]
 *
 * **Constraints:**
 *
 * *   `1 <= n <= 1000`
**/
public class Solution {
    private Map memo;

    public int[] beautifulArray(int n) {
        memo = new HashMap<>();
        return helper(n);
    }

    private int[] helper(int n) {
        if (n == 1) {
            memo.put(1, new int[] {1});
            return new int[] {1};
        }
        if (memo.containsKey(n)) {
            return memo.get(n);
        }
        int mid = (n + 1) / 2;
        int[] left = helper(mid);
        int[] right = helper(n - mid);
        int[] rst = new int[n];
        for (int i = 0; i < mid; i++) {
            rst[i] = left[i] * 2 - 1;
        }
        for (int i = mid; i < n; i++) {
            rst[i] = right[i - mid] * 2;
        }
        memo.put(n, rst);
        return rst;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy