Hackerrank,set、list时间复杂度问读

Problem Statement

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≤109

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.

Output Format

Output a single integer, the answer.

Sample Input

3 2
1 5 3
3 1
5 7

Sample Output

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.

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,安全通过!

2、我将seta、setb换成集合,运行,然后等了好久超时,好吧,以前写程序没碰到过这种问题。

查看disscussions,大家评论指出是时间复杂度的原因,x in list的复杂度为O(n),而x in set的复查度仅为O(1)。

https://wiki.python.org/moin/TimeComplexity 该页面指出了Python中各种数据结构的进行各种操作的时间复杂度。

3、在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中高手与菜鸟代码的差距。


你可能感兴趣的:(Hackerrank,set、list时间复杂度问读)