我正在尝试解决 GeeksClasses 中的问题,但我的提交有问题。我的代码有效,但他们说您的程序花费的时间比预期的要多。
给定一个整数数组。检查它是否包含总和为零的三元组。
输入的第一行包含一个整数T,表示测试用例的数量。然后是 T 个测试用例。每个测试用例的第一行包含一个整数 N,表示数组中元素的数量。每个测试用例的第二行包含数组的 N 个空格分隔值。
对于每个测试用例,如果存在三元组,则输出为 1,否则为 0
2
5
0 -1 2 -3 1
3
1 2 3
1
0
def isPair(arr,left,right,u):
while left < right:
if arr[left] + arr[right] < u:
left += 1
elif arr[left] + arr[right] == u:
return True
elif arr[left] + arr[right] > u:
right -= 1
return False
def findTriplets(a,n):
#code here
a = sorted(a)
for i in range(n):
if isPair(a,i+1,n-1,0-a[i]):
return 1
return 0
#driver code
if __name__=='__main__':
t=int(input())
for i in range(t):
n=int(input())
a=list(map(int,input().strip().split()))
print(findTriplets(a,n))
慕少森
白衣非少年
相关分类