452. Find Closest Element to Target in Sorted Array

EasyBinary SearchArrayBinary Search

Given a sorted array nums and an integer target, return the element in nums that is closest to target. If two elements are equidistant from target, return the smaller one.

Input: A sorted integer array nums and integer target.

Output: The element in nums closest to target.

Examples

Example 1
Input: [1,3,5,7,9], 4
Output: 3
Explanation: |3-4|=1, |5-4|=1 → tie → return smaller = 3.
Example 2
Input: [1,3,5,7,9], 6
Output: 5
Explanation: |5-6|=1 < |7-6|=1 → tie... actually |5-6|=1 and |7-6|=1, return smaller=5.
Example 3
Input: [1,3,5,7,9], 0
Output: 1
Explanation: 1 is smallest and closest to 0.

Constraints

Asked by

TCSInfosysWiproCognizantCapgemini
Solve this problem in the editor →