Problem Statementpython
There is an array of n integers, and 2 disjoint sets of m integers each A and B. You like all integers in A and dislike all integers in B. Your initial happiness is 0 and for each integer in the array, i, if i∈A, you add 1 to your happiness, if i∈B, you add −1 to your happiness, else your happiness does not change. Output your final happiness at the end.安全
Note that since A and B are sets, they have no repeated elements. But, the array might contain duplicate elements.数据结构
Constraints
1≤n≤105
1≤m≤105
1≤Any integer in the input≤109app
Input Format函数
First line contains n and m.
Second line contains n integers, the array.
Third and fourth lines contain m integers, A and B respectively.spa
Output Formatcode
Output a single integer, the answer.orm
Sample Inputci
3 2 1 5 3 3 1 5 7
Sample Outputelement
1
Explanation
You gain 1 unit of happiness for each 3 and 1 and lose 1 unit for 5 and 7 hence total happiness is 2−1=1.
一、个人第一种解法:
n, m = raw_input().split()
a = raw_input().split()
seta = set(raw_input().split())
setb = set(raw_input().split())
sum = 0
for x in a:
if x in seta:
sum += 1
elif x in setb:
sum -= 1
print sum
Ok,安全经过!
二、我将seta、setb换成集合,运行,而后等了很久超时,好吧,之前写程序没碰到过这种问题。
查看disscussions,你们评论指出是时间复杂度的缘由,x in list的复杂度为O(n),而x in set的复查度仅为O(1)。
https://wiki.python.org/moin/TimeComplexity 该页面指出了Python中各类数据结构的进行各类操做的时间复杂度。
三、在disscussions中看到大牛解决该题的代码。
raw_input()
array, a, b = [raw_input().split() for _ in range(3)]
a = set(a)
b = set(b) print
sum(1 if i in a else -1 if i in b else 0 for i in array)
用一个"_"可节省空间,sum函数用到了列表推导式,进一步说明了Pythoner中高手与菜鸟代码的差距。