Alice and Bob have candy bars of different sizes: A[i] is the size of the i-th bar of candy that Alice has, and B[j] is the size of the j-th bar of candy that Bob has.

Since they are friends, they would like to exchange one candy bar each so that after the exchange, they both have the same total amount of candy.  (The total amount of candy a person has is the sum of the sizes of candy bars they have.)

Return an integer array ans where ans[0] is the size of the candy bar that Alice must exchange, and ans[1] is the size of the candy bar that Bob must exchange.

If there are multiple answers, you may return any one of them.  It is guaranteed an answer exists.

原题地址: Fair Candy Swap

题意: 给两个数组A B,各选取一个数进行交换,使得数组A的和等于数组B的和,返回交换的两个数

例子:

Input: A = [1,1], B = [2,2]
Output: [1,2] # 交换之后 A = [1,2] B = [1, 2]

(1)求出两个数组的平均值,也就是最后两个数组的和

(2)遍历数组A,假设当前值是要交换的数A[i],那么数组B中要交换的数是 平均值 - (sum(A) - A[i]) , 并判断此数是否在数组B中.如果存在,返回这两个数

注意: 可能存在重复值,是否存在重复值对结果没有影响,为了减少遍历次数,可以用 set() 去重,并且获取元素的时间复杂度是O(1)

代码:

class Solution(object):
def fairCandySwap(self, A, B):
"""
:type A: List[int]
:type B: List[int]
:rtype: List[int]
"""
a, b , set_b = sum(A), sum(B), set(B)
mean = (a + b) / 2
for num in A:
target = mean - (a - num)
if 1<= target <= 100000 and target in set_b:
return [num, target]

时间复杂度:O(n)

遍历数组A为n次,判断一个数是否在set(B)中,需要1次,

空间复杂度:list转化为set,为O(n)

最新文章

  1. Percona 5.7安装
  2. 【面经】用递归方法对二叉树进行层次遍历 &amp;&amp; 二叉树深度
  3. Win7精简成功后的总结
  4. svn在linux下的使用(转)
  5. oracle 将查询到的数据插入表
  6. delphi 句柄
  7. Yii2的使用
  8. IDEA内置Git管理
  9. VS2015密钥
  10. 关于拓展jQuery功能插件的写法
  11. [转] iOS文字排版(CoreText)那些事儿
  12. Codeforces Round #283 (Div. 2) B. Secret Combination 暴力水题
  13. LeetCode: Word Search 解题报告
  14. Ubuntu下,dpkg安装出错的修复
  15. LabView和DLL中的参数问题
  16. SQL语言 之 数据查询
  17. MS15-051 修正版Exploit(Webshell可用)
  18. [Usaco2017 Open]Modern Art 2
  19. Dom4j 查找节点或属性
  20. mpvue 小程序加载不了图片 Error: Failed to load local image resource /images/xx.png the server responded with a status of 404 (HTTP/1.1 404 Not Found)

热门文章

  1. 洛谷 - P1198 - 最大数 - 线段树
  2. thrift配置——windows客户端与linux服务端通信(C++)
  3. POJ 2392【多重背包】
  4. Codeforces34C【尺取】
  5. spark 机器学习 朴素贝叶斯 原理(一)
  6. 第九篇 .NET高级技术ref、out
  7. 树的直径初探+Luogu P3629 [APIO2010]巡逻【树的直径】By cellur925
  8. 数位dp真&#183;浅谈 By cellur925
  9. 洛谷 P3960 列队
  10. Jumping on Walls CodeForces - 198B