TGViewer
Java | LeetCode Java | LeetCode @easy_java_task · 6.44K subscribers
Post #1864 871
Задача: 1338. Reduce Array Size to The Half
Сложность: medium

Дан массив целых чисел arr. Вы можете выбрать набор чисел и удалить все вхождения этих чисел из массива.

Верните минимальный размер набора, чтобы было удалено не менее половины целых чисел из массива.

Пример:
Input: arr = [3,3,3,3,5,5,5,2,2,7]
Output: 2
Explanation: Choosing {3,7} will make the new array [5,5,5,2,2] which has size 5 (i.e equal to half of the size of the old array).
Possible sets of size 2 are {3,5},{3,2},{5,2}.
Choosing set {2,7} is not possible as it will make the new array [3,3,3,3,5,5,5] which has a size greater than half of the size of the old array.


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

1⃣Отсортировать массив и создать список подсчета количества вхождений каждого числа.

2⃣Отсортировать список подсчета в порядке убывания.

3⃣Удалять числа из массива, начиная с наибольшего количества вхождений, пока не будет удалено не менее половины чисел массива. Вернуть размер множества удаленных чисел.

😎 Решение:
class Solution {
public int minSetSize(int[] arr) {
Arrays.sort(arr);
List<Integer> counts = new ArrayList<>();
int currentRun = 1;
for (int i = 1; i < arr.length; i++) {
if (arr[i] == arr[i - 1]) {
currentRun += 1;
continue;
}
counts.add(currentRun);
currentRun = 1;
}
counts.add(currentRun);
Collections.sort(counts);
Collections.reverse(counts);
int numbersRemovedFromArr = 0;
int setSize = 0;
for (int count : counts) {
numbersRemovedFromArr += count;
setSize += 1;
if (numbersRemovedFromArr >= arr.length / 2) {
break;
}
}
return setSize;
}
}


Ставь 👍 и забирай 📚 Базу знаний
More from @easy_java_task
  1. Oct 13, 2026Post #2296
  2. Oct 13, 2026Задача: 1120. Maximum Average Subtree Сложность: medium Дан корень бинарного дерева. Верни…
  3. Oct 13, 2026Post #2294
  4. Oct 12, 2026Задача: 1413. Minimum Value to Get Positive Step by Step Sum Сложность: easy Дан массив це…
  5. Oct 11, 2026Задача: 672. Bulb Switcher II Сложность: medium Есть комната с n лампочками, пронумерованн…
  6. Oct 10, 2026Задача: 723. Candy Crush Сложность: medium Этот вопрос касается реализации базового алгори…
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 →