1. 最直觀的方法,把list存成dictionary,key爲color,value爲color出現的次數,而後循環一個個導出。
def sortcolor2(colors,k):
count={}
for c in colors:
if c not in count:
count[c]=0
else:
count[c]+=1
print(count)
index= 0
i = 1
for i in range(1,k+1):
while(count[i]>=0):
colors[index]=i
index+=1
count[i]-=1
i +=1
return colors
時間複雜度爲O(N)
2. 另一種方法比較難以理解。我的理解是,計數法。把每個color對應的bucket當成計數。每一次讓當前值變成bucket對應的值,bucket值變爲-1,表示計數一次。若讀到bucket爲負數,表示已計數,bucket值減一,當前值也就是color[i]爲0。如此到。最後,會得出一個list表示每種color的計數。而後需要倒置導出。時間複雜度爲O(nlogK)。確實好難理解啊。做一天僵半天。想知道是怎麼想到這樣的解法的。
class Solution:
"""
@param colors: A list of integer
@param k: An integer
"""
def sortColors2(self, colors, k):
# write your code here
i = 0
n=len(colors)
while i<n:
nums=colors[i]
if colors[i]>0:
if colors[nums-1]>0:
colors[i]=colors[nums-1]
colors[nums-1]=-1
i -= 1
else:
colors[nums-1]-=1
colors[i]=0
i +=1
i=len(colors)-1
k=i
while i>=0:
@return: nothing
if colors[i]<0:
temp=k+colors[i]
第三種 快排。以後再補。