LeetCode in Kotlin

932. Beautiful Array

Medium

An array nums of length n is beautiful if:

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:

Solution

class Solution {
    private var memo: MutableMap<Int, IntArray>? = null
    fun beautifulArray(n: Int): IntArray? {
        memo = HashMap()
        return helper(n)
    }

    private fun helper(n: Int): IntArray? {
        if (n == 1) {
            memo!![1] = intArrayOf(1)
            return intArrayOf(1)
        }
        if (memo!!.containsKey(n)) {
            return memo!![n]
        }
        val mid = (n + 1) / 2
        val left = helper(mid)
        val right = helper(n - mid)
        val rst = IntArray(n)
        for (i in 0 until mid) {
            rst[i] = left!![i] * 2 - 1
        }
        for (i in mid until n) {
            rst[i] = right!![i - mid] * 2
        }
        memo!![n] = rst
        return rst
    }
}
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy