diff --git a/leetcode/2401-2500/2491.Divide-Players-Into-Teams-of-Equal-Skill/Solution.go b/leetcode/2401-2500/2491.Divide-Players-Into-Teams-of-Equal-Skill/Solution.go index ebe45e34..387d3dd7 100644 --- a/leetcode/2401-2500/2491.Divide-Players-Into-Teams-of-Equal-Skill/Solution.go +++ b/leetcode/2401-2500/2491.Divide-Players-Into-Teams-of-Equal-Skill/Solution.go @@ -19,3 +19,32 @@ func Solution(skill []int) int64 { } return ans } + +func Solution1(skill []int) int64 { + l := len(skill) / 2 + sum := 0 + for _, n := range skill { + sum += n + } + if sum%l != 0 { + return -1 + } + target := sum / l + count := make(map[int]int) + for _, n := range skill { + count[n]++ + } + + ans := int64(0) + for k, c := range count { + need := target - k + if need == k && c&1 == 1 { + return -1 + } + if v, ok := count[need]; !ok || v != c { + return -1 + } + ans += int64(k) * int64(need) * int64(c) + } + return ans / 2 +} diff --git a/leetcode/2401-2500/2491.Divide-Players-Into-Teams-of-Equal-Skill/Solution_test.go b/leetcode/2401-2500/2491.Divide-Players-Into-Teams-of-Equal-Skill/Solution_test.go index 5c922e50..005283bf 100644 --- a/leetcode/2401-2500/2491.Divide-Players-Into-Teams-of-Equal-Skill/Solution_test.go +++ b/leetcode/2401-2500/2491.Divide-Players-Into-Teams-of-Equal-Skill/Solution_test.go @@ -30,6 +30,30 @@ func TestSolution(t *testing.T) { } } +func TestSolution1(t *testing.T) { + // 测试用例 + cases := []struct { + name string + inputs []int + expect int64 + }{ + {"TestCase1", []int{3, 2, 5, 1, 3, 4}, 22}, + {"TestCase2", []int{3, 4}, 12}, + {"TestCase3", []int{1, 1, 2, 3}, -1}, + } + + // 开始测试 + for i, c := range cases { + t.Run(c.name+" "+strconv.Itoa(i), func(t *testing.T) { + got := Solution1(c.inputs) + if !reflect.DeepEqual(got, c.expect) { + t.Fatalf("expected: %v, but got: %v, with inputs: %v", + c.expect, got, c.inputs) + } + }) + } +} + // 压力测试 func BenchmarkSolution(b *testing.B) { }