Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

公平的糖果棒交换 #105

Open
yankewei opened this issue Feb 1, 2021 · 1 comment
Open

公平的糖果棒交换 #105

yankewei opened this issue Feb 1, 2021 · 1 comment
Labels
哈希表 题目包含哈希表解法 数组 题目类型为数组 简单 题目难度为简单

Comments

@yankewei
Copy link
Owner

yankewei commented Feb 1, 2021

爱丽丝和鲍勃有不同大小的糖果棒:A[i] 是爱丽丝拥有的第 i 根糖果棒的大小,B[j] 是鲍勃拥有的第 j 根糖果棒的大小。

因为他们是朋友,所以他们想交换一根糖果棒,这样交换后,他们都有相同的糖果总量。(一个人拥有的糖果总量是他们拥有的糖果棒大小的总和。)

返回一个整数数组 ans,其中 ans[0] 是爱丽丝必须交换的糖果棒的大小,ans[1] 是 Bob 必须交换的糖果棒的大小。

如果有多个答案,你可以返回其中任何一个。保证答案存在。

示例 1:

输入:A = [1,1], B = [2,2]
输出:[1,2]

示例 2:

输入:A = [1,2], B = [2,3]
输出:[1,2]

示例 3:

输入:A = [2], B = [1,3]
输出:[2,3]

示例 4:

输入:A = [1,2,5], B = [2,4]
输出:[5,4]

提示:

  • 1 <= A.length <= 10000
  • 1 <= B.length <= 10000
  • 1 <= A[i] <= 100000
  • 1 <= B[i] <= 100000
  • 保证爱丽丝与鲍勃的糖果总量不同。
  • 答案肯定存在。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/fair-candy-swap
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

@yankewei yankewei added 简单 题目难度为简单 数组 题目类型为数组 labels Feb 1, 2021
@yankewei
Copy link
Owner Author

yankewei commented Feb 1, 2021

这个题,最重要的就是要认真读题,只需要交换一次就可以成功。所以不用考虑多次交换的事情

func fairCandySwap(A []int, B []int) []int {
    var sumA int
    for _, v := range A {
	sumA += v
    }
    var sumB int
    setB := make(map[int]struct{}, len(B))
    for _, v := range B {
	sumB += v
	setB[v] = struct{}{}
    }
    avg := (sumA + sumB)/2
    // 因为题目说交换一次,并且肯定会有答案,就是说,当 sumA 与 avg 之间的差值可经过交换元素来弥补
    delta := avg-sumA
    for _, v := range A {
	if _, e := setB[v+delta]; e {
	    return []int{v,v+delta}
	}
    }
    return []int{}
}

@yankewei yankewei added the 哈希表 题目包含哈希表解法 label Feb 1, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
哈希表 题目包含哈希表解法 数组 题目类型为数组 简单 题目难度为简单
Projects
None yet
Development

No branches or pull requests

1 participant