#找出连续数组中唯一的重复元素
#方法1:先排序再进行两两比较
def findDup(array):
if array==None:
return -1
length=len(array)
for i in range(length):
for j in range(i+1,length):
if array[j]>array[i]:
array[i],array[j]=array[j],array[i]
for k in range(length-1):
if array[k]==array[k+1]:
print(array[k])
if __name__ == '__main__':
array=[1,2,4,6,5,3,5,7,8,0,9]
findDup(array)
#方法2:利用集合去重特性,作差计算重复数字
def findDup(array):
if array==None:
return -1
s=set(array)
sum1=sum(s)
sum2=sum(array)
dup=sum2-sum1
print(dup)
if __name__ == '__main__':
array=[1,2,4,6,5,3,5,7,8,0,9]
findDup(array)
#方法3:取异或的方法
def findDup(array):
if array==None:
return -1
length=len(array)
i,result=0,0
while i<length:
result^=array[i]
i+=1
j=1
while j<length:
result^=j
j+=1
print(result)
if __name__ == '__main__':
array=[1,2,4,6,5,3,5,7,8,9]
findDup(array)
python三种方法找出连续数组中唯一重复元素(如[1,2,4,6,5,3,5,7,8,0,9]中唯一重复元素为5)
最新推荐文章于 2023-10-31 20:38:49 发布