TGViewer
Python | LeetCode Python | LeetCode @easy_python_task · 9.01K subscribers
Post #1649 1.06K
Задача: 528. Random Pick with Weight
Сложность: medium

Вам дан массив положительных целых чисел w, где w[i] описывает вес индекса i.
Вам нужно реализовать функцию pickIndex(), которая случайным образом выбирает индекс в диапазоне [0, w.length - 1] (включительно) и возвращает его. Вероятность выбора индекса i равна w[i] / sum(w).

Например, если w = [1, 3], вероятность выбора индекса 0 составляет 1 / (1 + 3) = 0.25 (т.е. 25%), а вероятность выбора индекса 1 составляет 3 / (1 + 3) = 0.75 (т.е. 75%).

Пример:
Input
["Solution","pickIndex","pickIndex","pickIndex","pickIndex","pickIndex"]
[[[1,3]],[],[],[],[],[]]
Output
[null,1,1,1,1,0]

Explanation
Solution solution = new Solution([1, 3]);
solution.pickIndex(); // return 1. It is returning the second element (index = 1) that has a probability of 3/4.
solution.pickIndex(); // return 1
solution.pickIndex(); // return 1
solution.pickIndex(); // return 1
solution.pickIndex(); // return 0. It is returning the first element (index = 0) that has a probability of 1/4.

Since this is a randomization problem, multiple answers are allowed.
All of the following outputs can be considered correct:
[null,1,1,1,1,0]
[null,1,1,1,1,1]
[null,1,1,1,0,0]
[null,1,1,1,0,1]
[null,1,0,1,0,0]
......
and so on.


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

1⃣ Инициализация и предобработка весов:
В конструкторе создайте массив накопительных сумм prefixSums, где каждая позиция будет содержать сумму всех предыдущих весов до текущего индекса включительно.
Также в конструкторе сохраните общую сумму весов totalSum.

2⃣ Генерация случайного числа и выбор индекса:
В функции pickIndex() сгенерируйте случайное число в диапазоне от 0 до общей суммы весов totalSum.
Используйте линейный поиск, чтобы найти первый индекс в prefixSums, который больше или равен сгенерированному числу.

3⃣ Возврат результата:
Верните найденный индекс.

😎 Решение:
import random

class Solution:
def __init__(self, w: List[int]):
self.prefixSums = []
prefixSum = 0
for weight in w:
prefixSum += weight
self.prefixSums.append(prefixSum)
self.totalSum = prefixSum

def pickIndex(self) -> int:
target = self.totalSum * random.random()
for i, prefixSum in enumerate(self.prefixSums):
if target < prefixSum:
return i
return len(self.prefixSums) - 1


Ставь 👍 и забирай 📚 Базу знаний
  • 🔥 1
More from @easy_python_task
  1. Oct 18, 2026Post #2452
  2. Oct 17, 2026Задача: 409. Longest Palindrome Сложность: easy Если задана строка s, состоящая из строчны…
  3. Oct 17, 2026Задача: 1539. Kth Missing Positive Number Сложность: easy Дан массив arr из положительных…
  4. Oct 16, 2026Задача: 1236. Web Crawler Сложность: medium Учитывая url startUrl и интерфейс HtmlParser,…
  5. Oct 15, 2026Задача: 1043. Partition Array for Maximum Sum Сложность: medium Если задан целочисленный м…
  6. Oct 15, 2026Задача: 1474. Delete N Nodes After M Nodes of a Linked List Сложность: 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 →