impl: q238, q380

This commit is contained in:
kanna5 2025-12-08 14:52:29 +09:00
parent cc7fb41dfc
commit 411a71bd16
4 changed files with 128 additions and 0 deletions

3
go.mod Normal file
View file

@ -0,0 +1,3 @@
module leetcode-go
go 1.25.5

View file

@ -0,0 +1,24 @@
package q238
func productExceptSelf(nums []int) []int {
ret := make([]int, len(nums))
// from left
t := 1
for i := range len(nums) - 1 {
t *= nums[i]
ret[i+1] = t
}
ret[0] = 1
// from right
t = 1
for i := len(nums) - 1; i > 0; i-- {
t *= nums[i]
ret[i-1] *= t
}
return ret
}
var _ = productExceptSelf

View file

@ -0,0 +1,32 @@
package q238
import (
"slices"
"testing"
)
func Test_productExceptSelf(t *testing.T) {
tests := []struct {
name string // description of this test case
// Named input parameters for target function.
nums []int
want []int
}{
{
nums: []int{1, 2, 3, 4},
want: []int{24, 12, 8, 6},
},
{
nums: []int{-1, 1, 0, -3, 3},
want: []int{0, 0, 9, 0, 0},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := productExceptSelf(tt.nums)
if !slices.Equal(got, tt.want) {
t.Errorf("productExceptSelf() = %v, want %v", got, tt.want)
}
})
}
}

View file

@ -0,0 +1,69 @@
package q380
import (
"math/rand"
"runtime/debug"
)
func init() {
debug.SetMemoryLimit(16 << 20)
}
var rng *rand.Rand = rand.New(rand.NewSource(42))
type RandomizedSet struct {
vals []int
idx map[int]int // the index of the element in vals
}
func Constructor() RandomizedSet {
return RandomizedSet{
vals: []int{},
idx: map[int]int{},
}
}
// Insert Inserts an item val into the set if not present. Returns true if the
// item was not present, false otherwise.
func (rs *RandomizedSet) Insert(val int) bool {
if _, present := rs.idx[val]; present {
return false
}
rs.idx[val] = len(rs.vals)
rs.vals = append(rs.vals, val)
return true
}
// Remove Removes an item val from the set if present. Returns true if the item
// was present, false otherwise.
func (rs *RandomizedSet) Remove(val int) bool {
idx, present := rs.idx[val]
if !present {
return false
}
delete(rs.idx, val)
idxLast := len(rs.vals) - 1
if idx != idxLast {
rs.vals[idx] = rs.vals[idxLast]
rs.idx[rs.vals[idx]] = idx
}
rs.vals = rs.vals[:idxLast]
return true
}
// GetRandom Returns a random element from the current set of elements (it's
// guaranteed that at least one element exists when this method is called).
// Each element must have the same probability of being returned.
func (rs *RandomizedSet) GetRandom() int {
i := rng.Intn(len(rs.vals))
return rs.vals[i]
}
/**
* Your RandomizedSet object will be instantiated and called as such:
* obj := Constructor();
* param_1 := obj.Insert(val);
* param_2 := obj.Remove(val);
* param_3 := obj.GetRandom();
*/