Redaksiya
Let be an input array. Iterate through all possible indices . Then, for each value of , find a pair of indices such that and . This can be achieved on a sorted array using the two-pointer technique in linear time.
Algorithm realization
Read the input data.
cin >> n >> x; v.resize(n); for (i = 0; i < n; i++) cin >> v[i];
Sort the input array.
sort(v.begin(), v.end());
Iterate through the values .
for (k = 0; k < n - 2; k++) {
Find a pair of indices such that and . Initialize the indices and .
i = k + 1; j = n - 1; s = x - v[k];
Use the two-pointer technique to find the desired pair .
while (i < j) { if (v[i] + v[j] == s) {
If the pair is found, print the desired triplet of numbers .
printf("%d %d %d\n", v[k], v[i], v[j]); return 0; }
If , then move pointer one position to the right;
If , then move pointer one position to the left;
if (v[i] + v[j] < s) i++; else j--; } }
If the triplet of numbers is not found, print .
cout << -1 << endl;
Python realization
Read the input data.
n, x = map(int, input().split()) v = list(map(int, input().split()))
Sort the input list.
v.sort()
Iterate through the values .
for k in range(n - 2):
Find a pair of indices such that and . Initialize the indices and .
i, j = k + 1, n – 1 s = x - v[k]
Use the two-pointer technique to find the desired pair .
while i < j: if v[i] + v[j] == s:
If the pair is found, print the desired triplet of numbers .
print(v[k], v[i], v[j]) exit(0)
If , then move pointer one position to the right;
If , then move pointer one position to the left;
elif v[i] + v[j] < s: i += 1 else: j -= 1
If the triplet of numbers is not found, print .
print(-1)