Solution: Find the Closest Number
Review various solution approaches to find the closest number to a given number in an array in detail.
We'll cover the following...
We'll cover the following...
Solution 1
A simple and straightforward solution to this problem would be to compute the absolute difference of the target from each array element iteratively while keeping track of the minimum difference encountered so far.
Explanation
- Lines 13–14: We initially save the first index of the array and its index as the
closestnumber. - Lines 18–22: While traversing the whole array, we store the
closestnumber and its index to thetarget. - Lines 25: We return the
closestelement from the array.
Time complexity
Since we have to go through each element one by one and compute its absolute difference, this solution is an ...