932. Beautiful Array

LeetCode medium original: C# #array #csharp #leetcode #medium #recursion
선택한 UI 언어에 맞게 문제 텍스트를 러시아어에서 번역합니다. 코드는 변경하지 않습니다.

배열 nums длины n красив, если: nums является перестановкой целых чисел в диапазоне [1, n]. Для каждого 0 <= i < j < n не существует индекса k с i < k < j, где 2 * nums[k] == nums[i] + nums[j]. Заgiven 정수 n, return любой красивый 배열 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++ 해법

자동 초안, 제출 전 검토
#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 на четные и нечетные индексы и создать 배열ы для них.

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

😎

Vacancies for this task

활성 채용 with overlapping task tags are 표시됨.

전체 채용
아직 활성 채용이 없습니다.