932. Beautiful Array

LeetCode medium оригинал: C# #array #csharp #leetcode #medium #recursion

Массив nums длины n красив, если: nums является перестановкой целых чисел в диапазоне [1, n]. Для каждого 0 <= i < j < n не существует индекса k с i < k < j, где 2 * nums[k] == nums[i] + nums[j]. Задано целое число n, верните любой красивый массив nums длины n. Для заданного n будет хотя бы один правильный ответ.

Пример:

Input: n = 4

Output: [2,1,4,3]

C# решение

сопоставлено/оригинал
public class Solution {
    public int[] BeautifulArray(int n) {
        return Construct(n).ToArray();
    }
    
    private List<int> Construct(int n) {
        if (n == 1) return new List<int> { 1 };
        var odd = Construct((n + 1) / 2).Select(x => 2 * x - 1).ToList();
        var even = Construct(n / 2).Select(x => 2 * x).ToList();
        odd.AddRange(even);
        return odd;
    }
}

C++ решение

auto-draft, проверить перед отправкой
#include <bits/stdc++.h>
using namespace std;

// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
class Solution {
public:
    public vector<int>& BeautifulArray(int n) {
        return Construct(n).ToArray();
    }
    
    private List<int> Construct(int n) {
        if (n == 1) return new List<int> { 1 };
        var odd = Construct((n + 1) / 2).Select(x => 2 * x - 1).ToList();
        var even = Construct(n / 2).Select(x => 2 * x).ToList();
        odd.AddRange(even);
        return odd;
    }
}

Java решение

сопоставлено/оригинал
import java.util.ArrayList;
import java.util.List;

class Solution {
    public int[] beautifulArray(int n) {
        List<Integer> result = construct(n);
        int[] resArray = new int[result.size()];
        for (int i = 0; i < result.size(); i++) {
            resArray[i] = result.get(i);
        }
        return resArray;
    }
    
    private List<Integer> construct(int n) {
        if (n == 1) {
            List<Integer> base = new ArrayList<>();
            base.add(1);
            return base;
        }
        List<Integer> odd = construct((n + 1) / 2);
        List<Integer> even = construct(n / 2);
        List<Integer> result = new ArrayList<>();
        for (int x : odd) {
            result.add(2 * x - 1);
        }
        for (int x : even) {
            result.add(2 * x);
        }
        return result;
    }
}

JavaScript решение

сопоставлено/оригинал
var beautifulArray = function(n) {
    const construct = (n) => {
        if (n === 1) return [1];
        const odd = construct(Math.ceil(n / 2)).map(x => 2 * x - 1);
        const even = construct(Math.floor(n / 2)).map(x => 2 * x);
        return [...odd, ...even];
    };
    return construct(n);
};

Go решение

сопоставлено/оригинал
package main

func beautifulArray(n int) []int {
    return construct(n)
}

func construct(n int) []int {
    if n == 1 {
        return []int{1}
    }
    odd := construct((n + 1) / 2)
    even := construct(n / 2)
    result := make([]int, 0, n)
    for _, x := range odd {
        result = append(result, 2 * x - 1)
    }
    for _, x := range even {
        result = append(result, 2 * x)
    }
    return result
}

Algorithm

Использовать рекурсивный метод для создания красивого массива.

Если длина массива равна 1, вернуть массив [1].

Разделить n на четные и нечетные индексы и создать массивы для них.

Объединить массивы, созданные для четных и нечетных индексов, в результирующий массив.

😎

Вакансии для этой задачи

Показаны активные вакансии с пересечением по тегам задачи.

Все вакансии
Активных вакансий пока нет.