A
A
A_Htke2020-11-11 15:48:20
Arrays
A_Htke, 2020-11-11 15:48:20

C: How to search for the nearest one in an array?

It is required to implement a search in the sorted array of the element closest to the given value.
The first line contains one integer N — the size of the sorted array
(1 <= N <= 10^5). Next, the elements of the array are written ( N integers, |Ai| <= 10^9). Then
an integer Q is written - the number of requests that need to be processed (1 <= Q <= 10^5). The remaining Q lines contain integers Yj that define search queries.
Requests should be processed as follows. For each number Yj, you need to find
such an element in the array A that the difference between it and Yj is minimal.
You need to output two space-separated integers to the output file: the index of the found element and the resulting minimum distance.
Array elements are numbered with indices from 0 to N − 1. If there are
several nearest elements, it is allowed to display the index of any of them. In this problem, the answer for each request must be found independently of all
other requests in O(log N) time in the worst case.
Is there a pretty solution?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
Wataru, 2020-11-11
@wataru

Binary search
Only it is necessary to slightly slightly change. At the end, you will end up on some element closest to the one you are looking for on the left or right.
So check left and 2 adjacent elements for the closest.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question