
- Главная
- Каталог
- Интернет технологии
- Golang | LeetCode
Статистика канала
Input: arr = [1,1,2,2,3,3,4,4,5,5], target = 8
Output: 20{}
package main
func minMalwareSpread(graph [][]int, initial []int) int {
dfs := func(node int, infected map[int]struct{}) {
for neighbor := 0; neighbor < len(graph); neighbor++ {
if graph[node][neighbor] == 1 {
if _, ok := infected[neighbor]; !ok {
infected[neighbor] = struct{}{}
dfs(neighbor, infected)
}
}
}
}
n := len(graph)
initialSet := make(map[int]struct{})
for _, v := range initial {
initialSet[v] = struct{}{}
}
sort.Ints(initial)
minInfected := int(^uint(0) >> 1)
bestNode := initial[0]
for _, node := range initial {
infected := make(map[int]struct{})
for k := range initialSet {
if k != node {
infected[k] = struct{}{}
}
}
for i := range initialSet {
if i != node {
dfs(i, infected)
}
}
if len(infected) < minInfected {
minInfected = len(infected)
bestNode = node
}
}
return bestNode
}{}
Ставь 👍 и забирай 📚 Базу знаний
Input: n = 8
Output: 3
Explanation: 8 -> 4 -> 2 -> 1{}
func integerReplacement(n int) int {
memo := make(map[int]int)
return helper(n, memo)
}
func helper(n int, memo map[int]int) int {
if n == 1 {
return 0
}
if val, exists := memo[n]; exists {
return val
}
if n % 2 == 0 {
memo[n] = 1 + helper(n/2, memo)
} else {
memo[n] = 1 + min(helper(n+1, memo), helper(n-1, memo))
}
return memo[n]
}
func min(a, b int) int {
if a < b {
return a
}
return b
}{}
Ставь 👍 и забирай 📚 Базу знаний
Input: m = 3, n = 7
Output: 28{}
func uniquePaths(m int, n int) int {
if m == 1 || n == 1 {
return 1
}
return uniquePaths(m-1, n) + uniquePaths(m, n-1)
}{}
Ставь 👍 и забирай 📚 Базу знаний
Input: word = "a"
Output: ["1","a"]{}
package main
import (
"fmt"
"strconv"
)
func generateAbbreviations(word string) []string {
n := len(word)
var result []string
for x := 0; x < (1 << n); x++ {
result = append(result, abbr(word, x))
}
return result
}
func abbr(word string, x int) string {
var builder []byte
k := 0
for i := 0; i < len(word); i, x = i+1, x>>1 {
if x&1 == 0 {
if k != 0 {
builder = append(builder, strconv.Itoa(k)...)
k = 0
}
builder = append(builder, word[i])
} else {
k++
}
}
if k != 0 {
builder = append(builder, strconv.Itoa(k)...)
}
return string(builder)
}
func main() {
word := "word"
fmt.Println(generateAbbreviations(word))
}{}
Ставь 👍 и забирай 📚 Базу знаний
Input: sticks = [5]
Output: 0
Explanation: There is only one stick, so you don't need to do anything. The total cost is 0.{}
import (
"container/heap"
)
type MinHeap []int
func (h MinHeap) Len() int { return len(h) }
func (h MinHeap) Less(i, j int) bool { return h[i] < h[j] }
func (h MinHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *MinHeap) Push(x interface{}) {
*h = append(*h, x.(int))
}
func (h *MinHeap) Pop() interface{} {
old := *h
n := len(old)
x := old[n-1]
*h = old[0 : n-1]
return x
}
func connectSticks(sticks []int) int {
pq := &MinHeap{}
heap.Init(pq)
for _, stick := range sticks {
heap.Push(pq, stick)
}
totalCost := 0
for pq.Len() > 1 {
stick1 := heap.Pop(pq).(int)
stick2 := heap.Pop(pq).(int)
cost := stick1 + stick2
totalCost += cost
heap.Push(pq, cost)
}
return totalCost
}{}
Ставь 👍 и забирай 📚 Базу знаний
Input: head = [1,2,3,3,4,4,5]
Output: [1,2,5]{}
func deleteDuplicates(head *ListNode) *ListNode {
sentinel := &ListNode{0, head}
pred := sentinel
for head != nil {
if head.Next != nil && head.Val == head.Next.Val {
for head.Next != nil && head.Val == head.Next.Val {
head = head.Next
}
pred.Next = head.Next
} else {
pred = pred.Next
}
head = head.Next
}
return sentinel.Next
}{}
Ставь 👍 и забирай 📚 Базу знаний
Input: arr = [1,2,3,4,5], k = 4, x = 3
Output: [1,2,3,4]{}
func findClosestElements(arr []int, k int, x int) []int {
left, right := 0, len(arr) - k
for left < right {
mid := (left + right) / 2
if x - arr[mid] > arr[mid + k] - x {
left = mid + 1
} else {
right = mid
}
}
return arr[left:left + k]
}{}
Ставь 👍 и забирай 📚 Базу знанийInput: matrix = [[3,7,8],[9,11,13],[15,16,17]]
Output: [15]
Explanation: 15 is the only lucky number since it is the minimum in its row and the maximum in its column.
func luckyNumbers(matrix [][]int) []int {
N := len(matrix)
M := len(matrix[0])
rowMin := make([]int, N)
for i := 0; i < N; i++ {
rMin := matrix[i][0]
for j := 1; j < M; j++ {
if matrix[i][j] < rMin {
rMin = matrix[i][j]
}
}
rowMin[i] = rMin
}
colMax := make([]int, M)
for i := 0; i < M; i++ {
cMax := matrix[0][i]
for j := 1; j < N; j++ {
if matrix[j][i] > cMax {
cMax = matrix[j][i]
}
}
colMax[i] = cMax
}
var luckyNumbers []int
for i := 0; i < N; i++ {
for j := 0; j < M; j++ {
if matrix[i][j] == rowMin[i] && matrix[i][j] == colMax[j] {
luckyNumbers = append(luckyNumbers, matrix[i][j])
}
}
}
return luckyNumbers
}{}
Ставь 👍 и забирай 📚 Базу знаний
Input: flights = [[0,1,1],[1,0,1],[1,1,0]], days = [[1,3,1],[6,0,3],[3,3,3]]
Output: 12
Explanation:
One of the best strategies is:
1st week : fly from city 0 to city 1 on Monday, and play 6 days and work 1 day.
(Although you start at city 0, we could also fly to and start at other cities since it is Monday.)
2nd week : fly from city 1 to city 2 on Monday, and play 3 days and work 4 days.
3rd week : stay at city 2, and play 3 days and work 4 days.
Ans = 6 + 3 + 3 = 12.{}
func maxVacationDays(flights [][]int, days [][]int) int {
n, k := len(flights), len(days[0])
memo := make([][]int, n)
for i := range memo {
memo[i] = make([]int, k)
for j := range memo[i] {
memo[i][j] = -1
}
}
return dfs(flights, days, memo, 0, 0)
}
func dfs(flights [][]int, days [][]int, memo [][]int, curCity, weekNo int) int {
n, k := len(flights), len(days[0])
if weekNo == k {
return 0
}
if memo[curCity][weekNo] != -1 {
return memo[curCity][weekNo]
}
maxVac := 0
for nextCity := 0; nextCity < n; nextCity++ {
if curCity == nextCity || flights[curCity][nextCity] == 1 {
maxVac = max(maxVac, days[nextCity][weekNo]+dfs(flights, days, memo, nextCity, weekNo+1))
}
}
memo[curCity][weekNo] = maxVac
return maxVac
}
func max(a, b int) int {
if a > b {
return a
}
return b
}{}
Ставь 👍 и забирай 📚 Базу знанийОтзывы канала
Каталог Телеграм-каналов для нативных размещений
Golang | LeetCode — это Telegam канал в категории «Интернет технологии», который предлагает эффективные форматы для размещения рекламных постов в Телеграмме. Количество подписчиков канала в 3.9K и качественный контент помогают брендам привлекать внимание аудитории и увеличивать охват. Рейтинг канала составляет 5.2, количество отзывов – 0, со средней оценкой 0.0.
Вы можете запустить рекламную кампанию через сервис Telega.in, выбрав удобный формат размещения. Платформа обеспечивает прозрачные условия сотрудничества и предоставляет детальную аналитику. Стоимость размещения составляет 2517.48 ₽, а за 0 выполненных заявок канал зарекомендовал себя как надежный партнер для рекламы в TG. Размещайте интеграции уже сегодня и привлекайте новых клиентов вместе с Telega.in!
Вы снова сможете добавить каналы в корзину из каталога
Комментарий