и посмотреть медиа
Golang | LeetCode
и посмотреть медиа
LeetCode tasks in Golang. Solutions with code and explanations.
LeetCode tasks in Golang. Solutions with code and explanations.
AI bot for text-to-speech and voice cloning in Telegram. Create audio using neural network quickly and easily.
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.
Задача: 398. Random Pick Index Сложность: medium Из целочисленного массива nums с возможными дубликатами случайным образом выведите индекс заданного целевого числа. Можно предположить, что заданное целевое число должно существовать в массиве. Реализация класса Solution: Solution(int[] nums) Инициализирует объект с массивом nums. int pick(int target) Выбирает случайный индекс i из nums, где nums[i] == target. Если существует несколько допустимых i, то каждый индекс должен иметь равную вероятность возврата. Пример: Input ["Solution", "pick", "pick", "pick"] [[[1, 2, 3, 3, 3]], [3], [1], [3]] Output [null, 4, 0, 2] 👨💻 Алгоритм: 1⃣Инициализируйте объект с массивом nums. Сохраните этот массив для дальнейшего использования. 2⃣Реализуйте метод pick(target), который выбирает случайный индекс i из массива nums, где nums[i] равен target. Если таких индексов несколько, каждый из них должен иметь равную вероятность быть выбранным. 3⃣Для реализации метода pick используйте алгоритм reservoir sampling для выбора случайного индекса. 😎 Решение: import ( "math/rand" "time" ) type Solution struct { nums []int } func Constructor(nums []int) Solution { rand.Seed(time.Now().UnixNano()) return Solution{nums: nums} } func (this *Solution) Pick(target int) int { count := 0 result := -1 for i, num := range this.nums { if num == target { count++ if rand.Intn(count) == count-1 { result = i } } } return result } Ставь 👍 и забирай 📚 Базу знаний
Открыть канал и посмотреть медиаOnly registered users can share their opinion.
Be the first to share your impression of this resource!