# 剑指offer 面试3题

# -*- coding:utf-8 -*-
class Solution:
# 这里要特别注意~找到任意重复的一个值并赋值到duplication[0]
# 函数返回True/False
def duplicate(self, numbers, duplication):
# write code here
if numbers==None or len(numbers)<=1:
return False
for i in range(len(numbers)):
if numbers[i]<0 or numbers[i]>len(numbers)-1:
return False

numbers.sort()
for i in range(len(numbers)-1):
if numbers[i]==numbers[i+1]:
duplication[0]=numbers[i]
return True
return False

# -*- coding:utf-8 -*-
class Solution:
# 这里要特别注意~找到任意重复的一个值并赋值到duplication[0]
# 函数返回True/False
def duplicate(self, numbers, duplication):
# write code here
if numbers==None or len(numbers)<=1:
return False

usedDic=set() #集合
for i in range(len(numbers)):
if numbers[i]<0 or numbers[i]>len(numbers)-1:
return False
if numbers[i] not in usedDic:
usedDic.add(numbers[i])
else:
duplication[0]=numbers[i]
return True
return False

# -*- coding:utf-8 -*-
class Solution:
# 这里要特别注意~找到任意重复的一个值并赋值到duplication[0]
# 函数返回True/False
def duplicate(self, numbers, duplication):
# write code here
if numbers==None or len(numbers)<=1:
return False

for i in range(len(numbers)):
if numbers[i]<0 or numbers[i]>len(numbers)-1:
return False

for i in range(len(numbers)):
while (numbers[i]!=i):
if numbers[i]==numbers[numbers[i]]:
duplication[0]=numbers[i]
return True
else:
temp=numbers[i]
numbers[i]=numbers[temp]
numbers[temp]=temp
return False

'''

'''

# 方法一：利用哈希表，时间复杂度O(n)，空间复杂度O(n)
# 方法二：二分查找的变形，如下，时间复杂度O(nlogn)，空间复杂度为O(1)

class Solution:
def duplicate(self, numbers):
# write code here
if not numbers or len(numbers)<=0:
return -1
start=1
end=len(numbers)-1
while start<=end:
middle=(end-start)//2+start
count=self.countRange(numbers,len(numbers),start,middle)
if end==start:
if count>1:
return start
else:
break
if count>middle-start+1:
end=middle
else:
start=middle+1
return -1

def countRange(self,numbers,length,start,end):
'''
计算数组中的元素大于等于start，小于等于end的元素的个数
'''
if not numbers:
return 0
count=0
for  i in range(length):
if numbers[i]>=start and numbers[i]<=end:
count+=1
return count

if __name__=="__main__":
print(Solution().duplicate([2,3,5,4,3,2,6,7]))

posted @ 2018-06-27 08:45  Fintech带你飞  阅读(3747)  评论(0编辑  收藏  举报