feat: saturday

This commit is contained in:
2025-12-14 12:40:54 -05:00
parent 22a39df9f9
commit 2a6e1677d6
7 changed files with 164 additions and 0 deletions

49
pkg/two_sum/main.go Normal file
View File

@@ -0,0 +1,49 @@
package two_sum
import (
"slices"
)
type Index struct {
Index int
Value int
}
func ByValue(a, b Index) int {
return a.Value - b.Value
}
func ToIndices(list []int) []Index {
result := []Index{}
for index, value := range list {
result = append(result, Index{index, value})
}
slices.SortFunc(result, ByValue)
return result
}
// https://leetcode.com/problems/two-sum/description/
func TwoSum(nums []int, target int) []int {
numbers := ToIndices(nums)
lower, upper := 0, len(numbers)-1
for lower < upper {
current_sum := numbers[lower].Value + numbers[upper].Value
if current_sum < target {
lower++
} else if current_sum > target {
upper--
} else {
return []int{
numbers[lower].Index,
numbers[upper].Index,
}
}
}
return nil
}

14
pkg/two_sum/main_test.go Normal file
View File

@@ -0,0 +1,14 @@
package two_sum_test
import (
"testing"
"git.maximhutz.com/practice/pkg/two_sum"
"github.com/stretchr/testify/assert"
)
func TestTwoSum(t *testing.T) {
assert.Equal(t, two_sum.TwoSum([]int{2, 7, 11, 15}, 9), []int{0, 1})
assert.Equal(t, two_sum.TwoSum([]int{3, 2, 4}, 6), []int{1, 2})
assert.Equal(t, two_sum.TwoSum([]int{3, 3}, 6), []int{0, 1})
}