и посмотреть медиа
JavaScript | LeetCode
и посмотреть медиа
LeetCode tasks and solutions in JavaScript. Ideal for interview preparation and improving algorithm skills.
LeetCode tasks and solutions in JavaScript. Ideal for interview preparation and improving algorithm skills.
AI bot for text-to-speech and voice cloning in Telegram. Create audio using neural network quickly and easily.
The channel is dedicated to solving LeetCode tasks in JavaScript. It contains code examples for popular algorithmic problems frequently encountered in interviews. The materials will help master data structures, sorting, dynamic programming, and other key topics. Suitable for junior and middle developers looking to improve their skills.
Задача: 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⃣ Возврат результата: Верните найденный индекс. 😎 Решение: class Solution { constructor(w) { this.prefixSums = new Array(w.length).fill(0); let prefixSum = 0; for (let i = 0; i < w.length; i++) { prefixSum += w[i]; this.prefixSums[i] = prefixSum; } this.totalSum = prefixSum; } pickIndex() { const target = this.totalSum * Math.random(); for (let i = 0; i < this.prefixSums.length; i++) { if (target < this.prefixSums[i]) { return i; } } return this.prefixSums.length - 1; } } Ставь 👍 и забирай 📚 Базу знаний
Открыть канал и посмотреть медиаOnly registered users can share their opinion.
Be the first to share your impression of this resource!