Redaksiya
Let be the input array of numbers. Initialize pointers to the beginning of the array and to the end of the array. The array is already sorted according to the problem conditions.
While pointers and do not meet, perform the following actions:
If , then the desired pair of elements is found. Print it and terminate the program.
If , then move pointer one position to the right. In this case, the sum will increase;
If , then move pointer one position to the left. In this case, the will decrease;
Example
Let’s consider the first test. Initialize the pointers. Simulate the algorithm’s operation. The value of , we are looking for two numbers with a sum of .
Algorithm realization
Read the input data.
scanf("%d %d", &n, &x); v.resize(n); for (i = 0; i < n; i++) scanf("%d", &v[i]);
Initialize the pointers.
int i = 0, j = v.size() - 1;
Move pointer forward and pointer backward.
while (i < j) {
If , then the desired pair of elements is found. Print it and terminate the program.
if (v[i] + v[j] == x) { printf("YES\n"); 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] < x) i++; else j--; }
If the desired pair is not found, print "NO".
printf("NO\n");
Java realization
import java.util.*; public class Main { public static void main(String[] args) { Scanner con = new Scanner(System.in); int n = con.nextInt(); int x = con.nextInt(); int v[] = new int[n]; for(int i = 0; i < n; i++) v[i] = con.nextInt(); int i = 0, j = n - 1; while (i < j) { if (v[i] + v[j] == x) { System.out.println("YES"); return; } if (v[i] + v[j] < x) i++; else j--; } System.out.println("NO"); con.close(); } }
Python realization
Read the input data.
n, x = map(int,input().split()) lst = list(map(int,input().split()))
Initialize the pointers.
i = 0 j = n – 1
Move pointer forward and pointer backward.
while (i < j):
If , then the desired pair of elements is found. Print it and terminate the program.
if (lst[i] + lst[j] == x): print("YES") exit()
If , then move pointer one position to the right;
If , then move pointer one position to the left;
if (lst[i] + lst[j] < x): i += 1 else: j -= 1
If the desired pair is not found, print "NO".
print("NO")