Nearest Element in Sorted Array
EasyPractice library · +10 XPbinary searchsorted arrays
Given a sorted array of N distinct integers and a target integer T, find the element in the array that is closest in value to T. If there are two elements equally close to T (one smaller and one larger), choose the smaller one.
Input
The first line contains two integers N and T, where N is the size of the array and T is the target value. The second line contains N distinct integers, sorted in ascending order, representing the array.
Output
Print a single integer, the element in the array closest to T, with the tie-breaking rule applied.
Constraints
1 <= N <= 1000 -10^9 <= T <= 10^9 -10^9 <= array elements <= 10^9
Time limit 1 s (native code; slower languages get more)Memory 256 MB14 hidden tests
Example 1
Input
5 10 2 5 8 13 17
Output
8
10 is closest to 8 and 13. 8 is smaller, so 8 is chosen.
Example 2
Input
5 15 2 5 8 13 17
Output
13
15 is closest to 13 and 17. 13 is smaller, so 13 is chosen.
Hints
# Read the input from stdin and print the answer.
import sys
def main():
data = sys.stdin.read().split()
# your code here
main()
Example 1 input
5 10 2 5 8 13 17
Example 2 input
5 15 2 5 8 13 17