Logo
TGCATALOG
Catalog Collections Blog
Golang | LeetCode

Golang | LeetCode

LeetCode tasks in Golang. Solutions with code and explanations.

No ratings
376
02.12.2026
376
02.12.2026
No ratings
376
02.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
🔒Открыть пост
и посмотреть медиа
Задача: 787. Cheapest Flights Within K Stops Сложность: medium Есть n городов, соединенных некоторым количеством рейсов. Вам дан массив flights, где flights[i] = [fromi, toi, pricei] указывает на то, что существует рейс из города fromi в город toi с ценой pricei. Также даны три целых числа src, dst и k. Верните самую дешевую цену от src до dst с не более чем k остановками. Если такого маршрута нет, верните -1. Пример: Input: n = 4, flights = [[0,1,100],[1,2,100],[2,0,100],[1,3,600],[2,3,200]], src = 0, dst = 3, k = 1 Output: 700 Explanation: The graph is shown above. The optimal path with at most 1 stop from city 0 to 3 is marked in red and has cost 100 + 600 = 700. Note that the path through cities [0,1,2,3] is cheaper but is invalid because it uses 2 stops. 👨💻 Алгоритм: 1⃣Создайте список смежности, где adj[X] содержит всех соседей узла X и соответствующую цену, которую нужно заплатить, чтобы перейти к соседу. Инициализируйте массив dist, хранящий минимальную цену для достижения узла из узла src. Инициализируйте его большими значениями. Инициализируйте очередь, хранящую пары {node, distance}. Изначально очередь должна содержать только {src, 0}. Создайте переменную stops и установите ее значение равным 0. 2⃣Выполняйте поиск в ширину (BFS), пока очередь не станет пустой или пока stops > k. Итерируйте по всем узлам на определенном уровне. Это будет сделано путем запуска вложенного цикла и посещения всех узлов, которые в данный момент находятся в очереди. В каждой паре {node, distance} итерируйте по всем соседям узла. Для каждого соседа проверьте, меньше ли dist[neighbor] чем distance + цена ребра. Если это так, обновите dist[neighbor] и добавьте {neighbor, dist[neighbor]} в очередь. 3⃣После итерации по всем узлам на текущем уровне увеличьте stops на один. Мы посетили все узлы на определенном уровне и готовы посетить следующий уровень узлов. Когда мы достигнем условия, при котором либо очередь станет пустой, либо stops == k, у нас будет наш ответ в dist[dst]. Если dist[dst] не изменилось с начального большого значения, значит, мы никогда не достигли его, и следует вернуть -1. 😎 Решение: package main import ( "container/heap" "math" ) type Edge struct { to, cost int } type Item struct { node, cost, stops int } type PriorityQueue []*Item func (pq PriorityQueue) Len() int { return len(pq) } func (pq PriorityQueue) Less(i, j int) bool { return pq[i].cost < pq[j].cost } func (pq PriorityQueue) Swap(i, j int) { pq[i], pq[j] = pq[j], pq[i] } func (pq *PriorityQueue) Push(x interface{}) { *pq = append(*pq, x.(*Item)) } func (pq *PriorityQueue) Pop() interface{} { old := *pq n := len(old) item := old[n-1] *pq = old[0 : n-1] return item } func findCheapestPrice(n int, flights [][]int, src int, dst int, k int) int { adj := make([][]Edge, n) for _, flight := range flights { adj[flight[0]] = append(adj[flight[0]], Edge{flight[1], flight[2]}) } dist := make([]int, n) for i := range dist { dist[i] = math.MaxInt32 } pq := &PriorityQueue{} heap.Init(pq) heap.Push(pq, &Item{src, 0, 0}) for pq.Len() > 0 { item := heap.Pop(pq).(*Item) node, cost, stops := item.node, item.cost, item.stops if node == dst { return cost } if stops > k { continue } for _, edge := range adj[node] { newCost := cost + edge.cost if newCost < dist[edge.to] { dist[edge.to] = newCost heap.Push(pq, &Item{edge.to, newCost, stops + 1}) } } } return -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