Solution: Find the Closest Number
This review discusses the solution of the "find the closest number challenge" in detail.
We'll cover the following...
We'll cover the following...
Solution: 1
A simple and straight-forward solution to this problem would be to compute the absolute difference of the target from each list element iteratively, while keeping track of the minimum difference encountered so far.
Explanation
- Line 9-10: Initially saved the first index of the list and its index as the
closestnumber - Line 13-15: While traversing the whole list, we are storing the more
closestnumber and its index to thetarget - Line 17: Returning the
closestelement from the list
Time complexity
Since we have to go through each element one by one and compute its absolute difference, this solution is an ...