Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 2e736b8

Browse files
committed
update:888
1 parent e8837a6 commit 2e736b8

File tree

2 files changed

+35
-1
lines changed

2 files changed

+35
-1
lines changed

‎problems/0888.fair-candy-swap/README.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,3 +43,8 @@
4343
链接:https://leetcode-cn.com/problems/fair-candy-swap
4444
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
4545
```
46+
47+
根据题意,两边和相等,设A需要交换的为x,B需要交换的为y,则有
48+
49+
>sumA-x+y=sumB-y+x
50+

‎problems/0888.fair-candy-swap/run.go‎

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,38 @@
11
package swap
22

3-
funcRun() {
3+
import"fmt"
44

5+
func Run() {
6+
A := []int{1, 2, 5}
7+
B := []int{2, 4}
8+
res := fairCandySwap(A, B)
9+
fmt.Println(res)
510
}
611

712
func fairCandySwap(A []int, B []int) []int {
13+
aSum := sum(A)
14+
bSum := sum(B)
15+
diff := aSum - bSum
16+
17+
res := make([]int, 2)
18+
checkB := make(map[int]bool, len(B))
19+
for _, i := range B {
20+
checkB[i] = true
21+
}
22+
for i := 0; i < len(A); i++ {
23+
res[0] = A[i]
24+
res[1] = A[i] - diff/2
25+
if checkB[res[1]] {
26+
return res
27+
}
28+
}
829
return nil
930
}
31+
32+
func sum(arr []int) int {
33+
s := 0
34+
for _, i := range arr {
35+
s += i
36+
}
37+
return s
38+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /