Алгоритмы: различия между версиями
Перейти к навигации
Перейти к поиску
Artem (обсуждение | вклад) |
Artem (обсуждение | вклад) |
||
Строка 66: | Строка 66: | ||
result.append(i) | result.append(i) | ||
return result | return result | ||
</pre> | |||
= merge intervals = | |||
<pre> | |||
package main | |||
import ( | |||
"fmt" | |||
"sort" | |||
) | |||
func mergeIntervals(input [][2]int) [][2]int { | |||
sort.Slice(input, func(i, j int) bool { | |||
return input[i][0] < input[j][0] || input[i][1] < input[j][1] | |||
}) | |||
var result [][2]int | |||
left := input[0][0] | |||
right := input[0][1] | |||
for i := 0; i < len(input); i++ { | |||
if right >= input[i][0] { | |||
right = input[i][1] | |||
} else { | |||
result = append(result, [2]int{left, right}) | |||
left = input[i][0] | |||
right = input[i][1] | |||
} | |||
} | |||
result = append(result, [2]int{left, right}) | |||
return result | |||
} | |||
func main() { | |||
input := [][2]int{{2, 8}, {2, 6}, {1, 3}, {8, 10}, {15, 18}} | |||
fmt.Println(input) | |||
fmt.Println(mergeIntervals(input)) | |||
} | |||
</pre> | </pre> |
Версия от 20:05, 19 ноября 2024
НОД и НОК
// fast! func gcd(a uint, b uint) uint { for a != 0 && b != 0 { if a > b { a = a % b } else { b = b % a } } return a + b } func gcd2(a uint, b uint) uint { for a != b { if a > b { a = a - b } else { b = b - a } } return a + b } func lcm(a uint, b uint) uint { return (a * b) / gcd(a, b) }
Bin Search
def search(arr, value): if not arr: return False left, right = 0, len(arr) - 1 while left <= right: mid = (left + right) // 2 if arr[mid] == value: return True elif arr[mid] < value: left = mid + 1 else: right = mid - 1 return False
np_random_choice
import random def np_random_choice(size, probes): cumsum = [sum(probes[:i+1]) for i, p in enumerate(probes)] result = [] for probe in range(size): rnd = random.random() i = -1 while rnd > 0: i += 1 rnd = rnd - cumsum[i] result.append(i) return result
merge intervals
package main import ( "fmt" "sort" ) func mergeIntervals(input [][2]int) [][2]int { sort.Slice(input, func(i, j int) bool { return input[i][0] < input[j][0] || input[i][1] < input[j][1] }) var result [][2]int left := input[0][0] right := input[0][1] for i := 0; i < len(input); i++ { if right >= input[i][0] { right = input[i][1] } else { result = append(result, [2]int{left, right}) left = input[i][0] right = input[i][1] } } result = append(result, [2]int{left, right}) return result } func main() { input := [][2]int{{2, 8}, {2, 6}, {1, 3}, {8, 10}, {15, 18}} fmt.Println(input) fmt.Println(mergeIntervals(input)) }