Skip to content

Commit

Permalink
Add solution and test-cases for problem 1497
Browse files Browse the repository at this point in the history
  • Loading branch information
0xff-dev committed Oct 1, 2024
1 parent ffaca5d commit 40b8fea
Show file tree
Hide file tree
Showing 3 changed files with 67 additions and 11 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# [1497.Check If Array Pairs Are Divisible by k][title]

## Description
Given an array of integers `arr` of even length `n` and an integer `k`.

We want to divide the array into exactly `n / 2` pairs such that the sum of each pair is divisible by `k`.

Return `true` If you can find a way to do that or `false` otherwise.

**Example 1:**

```
Input: arr = [1,2,3,4,5,10,6,7,8,9], k = 5
Output: true
Explanation: Pairs are (1,9),(2,8),(3,7),(4,6) and (5,10).
```

**Example 2:**

```
Input: arr = [1,2,3,4,5,6], k = 7
Output: true
Explanation: Pairs are (1,6),(2,5) and(3,4).
```

**Example 3:**

```
Input: arr = [1,2,3,4,5,6], k = 10
Output: false
Explanation: You can try all possible pairs to see that there is no way to divide arr into 3 pairs each with sum divisible by 10.
```

## 结语

如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-golang-algorithm][me]

[title]: https://leetcode.com/problems/check-if-array-pairs-are-divisible-by-k
[me]: https://github.com/kylesliu/awesome-golang-algorithm
Original file line number Diff line number Diff line change
@@ -1,5 +1,21 @@
package Solution

func Solution(x bool) bool {
return x
func Solution(arr []int, k int) bool {
count := make([]int, k)
for _, n := range arr {
t := n % k
if n < 0 {
t = k - (-n % k)
if t == k {
t = 0
}
}
count[t]++
}
for i := 1; i < k; i++ {
if count[i] != count[k-i] {
return false
}
}
return count[0]%2 == 0
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,30 +10,31 @@ func TestSolution(t *testing.T) {
// 测试用例
cases := []struct {
name string
inputs bool
arr []int
k int
expect bool
}{
{"TestCase", true, true},
{"TestCase", true, true},
{"TestCase", false, false},
{"TestCase1", []int{1, 2, 3, 4, 5, 10, 6, 7, 8, 9}, 5, true},
{"TestCase2", []int{1, 2, 3, 4, 5, 6}, 7, true},
{"TestCase3", []int{1, 2, 3, 4, 5, 6}, 10, false},
}

// 开始测试
for i, c := range cases {
t.Run(c.name+" "+strconv.Itoa(i), func(t *testing.T) {
got := Solution(c.inputs)
got := Solution(c.arr, c.k)
if !reflect.DeepEqual(got, c.expect) {
t.Fatalf("expected: %v, but got: %v, with inputs: %v",
c.expect, got, c.inputs)
t.Fatalf("expected: %v, but got: %v, with inputs: %v %v",
c.expect, got, c.arr, c.k)
}
})
}
}

// 压力测试
// 压力测试
func BenchmarkSolution(b *testing.B) {
}

// 使用案列
// 使用案列
func ExampleSolution() {
}

0 comments on commit 40b8fea

Please sign in to comment.