''' 美团一面面试题 1.写出快速排序算法 2.给定数组和一个固定的数值sum,输出2个和为固定数值的数值对 (就是说和为sum,每组数值对中包含的元素有2个) 3.给定数组和一个固定的数值sum,输出3个和为固定数值的数值对 (就是说和为sum,每组数值对中包含的元素有3个) 美团每次面试是1个小时,考算法题的时间大约半小时,所考虑的主要是机器学习算法和编程算法题 ''' ''' 第二题:.给定数组a和一个固定的数值sum,输出两个数和为sum的数值对 算法步骤: 1.对数组进行排序 2.设置两个指针,初始位置分别指向起始索引为0和最后一个元素(索引为length-1) 如果a[0]+a[length-1]>sum: 则end向左移动 如果a[0]+a[length-1]<sum: 则start向右移动 否则:输出正确结果数对 3.终止条件:start指针和end指针指向同一个元素 时间复杂度 O(n) '''
a=[5,1,2,3,4,-5,11,-1,4,6,0]
a=sorted(a)
sum=6
start=0
end=len(a)-1
while(start<end):
if a[start]+a[end]>sum:
end-=1
elif a[start]+a[end]<sum:
start+=1
else:
print(a[start],a[end])
start+=1
end-=1
''' 第三题:.给定数组a和一个固定的数值sum,输出三个数和为sum的数值对 算法步骤:设置三个指针,第一个指针遍历了数组中的每个元素 1.对数组进行排序 2.初始位置分别指向起始索引为0和最后一个元素(索引为length-1) 如果a[0]+a[length-1]>sum: 则end向左移动 如果a[0]+a[length-1]<sum: 则start向右移动 否则:输出正确结果数对 3.终止条件:start指针和end指针指向同一个元素 时间复杂度 O(n**2) '''
a=[5,1,2,3,4,-5,11,-1,4,6,0]
a=sorted(a)
sum=6
temp=0
while(temp<len(a)):
temp_target=sum-a[temp]
start = 0
end = len(a) - 1
while(start<end):
# print('here',start,end)
if a[start]+a[end]==temp_target:
print(a[temp],a[start],a[end])
assert a[temp]+a[start]+a[end]==sum
start+=1
end-=1
elif a[start]+a[end]<temp_target:
start+=1
else:
end-=1
temp+=1