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


转载于:https://my.oschina.net/zpengseu/blog/541423

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值