leetcode

Description:

leetcode-888

Submission:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

class :
def fairCandySwap(self, A: List[int], B: List[int]) -> List[int]:
flag = (sum(A) - sum(B)) // 2 # 在if前计算好,能一定程度降低时间开销
for i in A:
for j in B:
if (i - j == flag):
return [i, j]

# 改进后(2548ms)
class :
def fairCandySwap(self, A: List[int], B: List[int]) -> List[int]:
flag = (sum(A) - sum(B)) // 2
for i in A:
if ((i-flag) in B):
return [i, i-flag]

# 一种比较快的做法(88ms),使用dict代替list进行查找
class :
def fairCandySwap(self, A: List[int], B: List[int]) -> List[int]:
dB = {k:True for k in B}

totalA = sum(A)
totalB = sum(B)

for i in A:
matching = totalB - totalA + 2*i
if int(matching/2) in dB:
return [i, int(matching/2)]

Acceptance:

ac