Hackerrank,set、list時間複雜度問讀

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中高手與菜鳥代碼的差距。

相關文章
相關標籤/搜索