TGViewer
Java | LeetCode Java | LeetCode @easy_java_task · 6.44K subscribers
Post #2172 486
Задача: 932. Beautiful Array
Сложность: medium

Массив 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]


👨‍💻 Алгоритм:

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

2⃣Если длина массива равна 1, вернуть массив [1].
Разделить n на четные и нечетные индексы и создать массивы для них.

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

😎 Решение:
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;
}
}


Ставь 👍 и забирай 📚 Базу знаний
More from @easy_java_task
  1. Oct 11, 2026Задача: 672. Bulb Switcher II Сложность: medium Есть комната с n лампочками, пронумерованн…
  2. Oct 10, 2026Post #2290
  3. Oct 10, 2026Задача: 723. Candy Crush Сложность: medium Этот вопрос касается реализации базового алгори…
  4. Oct 10, 2026Post #2288
  5. Oct 9, 2026Задача: 1266. Minimum Time Visiting All Points Сложность: easy На двумерной плоскости имее…
  6. Oct 7, 2026Задача: 350. Intersection of Two Arrays II Сложность: easy Даны два целочисленных массива…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →