Logo
TGCATALOG
Catalog Collections Blog
Golang | LeetCode

Golang | LeetCode

LeetCode tasks in Golang. Solutions with code and explanations.

No ratings
374
01.12.2026
374
01.12.2026
No ratings
374
01.12.2026
Safe redirect via bot
О канале

LeetCode tasks in Golang. Solutions with code and explanations.

Подписчиков —
Тематика Technology
Ссылка @easy_golang_task

We also recommend

Kekaton AI | Voiceover and voice clone
Kekaton AI | Voiceover and voice clone
Bot

AI bot for text-to-speech and voice cloning in Telegram. Create audio using neural network quickly and easily.

Description

Channel with solutions to popular LeetCode tasks in Go. Focus on optimized algorithms, efficient memory usage, and idiomatic code. Helps prepare for technical interviews in companies that use Golang.

Latest posts

Golang | LeetCode
Golang | LeetCode
🔒Открыть пост
и посмотреть медиа
Задача: 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 ( "math/rand" "time" ) type Solution struct { prefixSums []int totalSum int } func Constructor(w []int) Solution { prefixSums := make([]int, len(w)) prefixSum := 0 for i, weight := range w { prefixSum += weight prefixSums[i] = prefixSum } return Solution{prefixSums, prefixSum} } func (this *Solution) PickIndex() int { rand.Seed(time.Now().UnixNano()) target := float64(this.totalSum) * rand.Float64() for i, prefixSum := range this.prefixSums { if target < float64(prefixSum) { return i } } return len(this.prefixSums) - 1 } Ставь 👍 и забирай 📚 Базу знаний
Golang | LeetCode
FAQ

Open Golang | LeetCode in Telegram and press the Start button. No separate registration is required.

Yes. The service is designed to be straightforward: open the resource, follow the on-screen instructions and start using it.

No. You can use Golang | LeetCode directly in Telegram unless the resource description says otherwise.

Access depends on the resource. Check the current information in Telegram after opening Golang | LeetCode.

The exact features depend on the resource. Open Golang | LeetCode to see its current functions, content and access conditions.

Reviews for channel Golang | LeetCode

Log in to leave a review

Only registered users can share their opinion.

No reviews yet

Be the first to share your impression of this resource!

Similar resources

Loading
Switch to Light Theme
Home Catalog Collections Blog Login