题目:给定一个字符类型数组chas,判断chas中是否所有的字符都只出现过一次
要求1: 时间复杂度为O(N)的算法
思路:使用哈希表,记录每个字符出现是否在哈希表里出现,如果没有出现,则添加; 若重复出现则返回False
def isUnique(L):
if L == None or len(L) = 1:
return True
dict_ = {}
for item in L:
if item in dict_:
return False
else:
dict_[item] = 1
return True
要求2,空间复杂度为O(1)的算法
1、先将数组排序,再判断当前字符是否等于前一个字符即可
2、满足复杂度要求的算法只有非递归的堆排序
def HeapSort(L):
if L == None or len(L) == 1:
return
for i in range(len(L)):
heapInsert(L,i)
size = len(L)-1
swap(L,0,size)
while size > 0:
heapify(L,0,size)
size -= 1
swap(L,0,size)
def heapify(L,index,size):
left = 2 * index + 1
while left < size:
if left+1 < size and L[left+1] > L[left]:
largest = left + 1
else:
largest = left
if L[largest] > L[index]:
largest = largest
else:
largest = index
if largest == index:
break
swap(L,largest,index)
index = largest
left = 2 * left +1
def heapInsert(L,index):
while L[index] > L[int((index-1)/2)]:
swap(L,index,int((index-1)/2))
index = int((index-1)/2)
def swap(L,i,j):
tmp = L[i]
L[i] = L[j]
L[j] = tmp
def isUnique2(chas):
if chas == None or len(chas) == 1:
return True
HeapSort(chas)
for i in range(1,len(chas)):
if chas[i-1] == chas[i]:
return False
return True
若堆排序不是很了解,请参考我的另一篇文章:https://mp.csdn.net/postedit/94294293