Binary Search 2 - Find Nearest Index
You are given an array \(A\) of \(N\) unique integers in ascending order and \(Q\) queries. Each query will contain a integer \(Q_{i}\).
Output the index of the element \(Q_{i}\) in the array \(A\). If \(Q_{i}\) cannot be found in \(A\), output the index of the element closest to \(Q_{i}\). If two elements are equidistant from \(Q_{i}\), output the smaller index.
Each integer in \(A\) will be no larger than \(10^5\).
Constraints
\(1 \le N, Q, A_{i}, Q_{i} \le 10^5\)
Input Specification
The first line consists of \(N\) and \(Q\), representing the size of the array and the number of queries respectively.
The next \(N\) lines will each consist of a single integer \(A_{i}\), representing the integer at index \(i\) in the array \(A\). It is guaranteed that \(A\) is sorted in ascending order and contains no duplicates.
The following \(Q\) will each consist of a single integer \(Q_{i}\), representing an integer to look for in the array.
Output Specification
For each query \(Q_{i}\), output the index of \(Q_{i}\) in \(A\) on a new line. \(Q_{i}\) does not exist in \(A\), output the index of the element closest to \(Q_{i}\). If two elements are equidistant from \(Q_{i}\), output the smaller index.
Sample Input
5 3
1
3
6
7
9
3
5
8
Sample Output
1
2
3
Explanation for Sample Output
The number 3
is at index 1 in the array \([1,3,6,7,9]\).
Although 5
is not in the array, the nearest element is 6
, which is at index 2.
The nearest elements for 8
are 7
and 9
. Since 7
and 9
are both 1 away from 8
, the answer is the index for 7
since it is lower.
Comments