I'm trying to solve this problem: given an array of integers numbers , I'm requaierd to write a function closetNumbers(numbers) that finds the minimum absolute difference between any two integers in the array, and print the pair of integers that share the minimum absolute difference. When printing the pairs[i,j], they should be ordered ascending first by i, and then by j. The code I wrote passed some tests but I got a TLE on the majority of the tests (hidden tests). Im not sure why (maybe the nested loop is the problem?), but either way, I can't think of an idea how to not use nested loops. Any suggestions or ideas how to better the code (or why the TLE message) would be greatly appreciated.
attached the description of the question, list of the case tests, and also my code.
code:
def closestNumbers(numbers):
numbers.sort()
d=abs(numbers[0]-numbers[1])
ans=[]
for j in range(len(numbers)):
for i in range(j+1, len(numbers)):
res_1=abs(numbers[j]-numbers[i])
if (res_1 == d):
ans.append(numbers[j])
ans.append(numbers[i])
elif (res_1<d):
d=res_1
ans=[numbers[j],numbers[i]]
for k in range (0, len(ans), 2):
print (ans[k], ans[k+1])
return 0
Try this:
import math
from itertools import combinations
numbers = [2, 4, 6, 10]
def closestNumbers(numbers):
distance = math.pow(10, 6)
selected_pairs = []
for i in numbers:
if not (math.pow(-10, 9) <= i <= math.pow(10, 9)):
return
numbers.sort()
pairs = list(combinations(numbers, 2))
for pair in pairs:
new_distance = pair[1] - pair[0]
if (2 <= new_distance <= math.pow(10, 5)) and new_distance < distance:
selected_pairs = [pair]
distance = new_distance
elif (2 <= new_distance <= math.pow(10, 5)) and new_distance == distance:
selected_pairs.append(pair)
distance = new_distance
for selected_pair in selected_pairs:
print(f"{selected_pair[0]} {selected_pair[1]}")
closestNumbers(numbers)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.