1. Bianry Search for closest number problem
- Input : ordred list of integers, a given number
Ouptut : find the the closest number to the given number
solution in python
123456789101112131415# recursion solutiondef solve(arr, num, start=0):# 01. base case : size() <= 3if len(arr) <= 3:minVal = min([abs(x - num) for x in arr])for i in range(len(arr)):if minVal == abs(arr[i] - num):return start + i# 02. check the mid value then exclude the wrong sidemid = int(len(arr)/2)if arr[mid] < num:return solve(arr[mid + 1:], num, start + mid + 1)else:return solve(arr[:mid + 1], num, start)solution in C++
12345678910111213141516171819// recursive solutionint solve(vector<int> arr, int num, int start, int end){// 01. base case : size() <= 3if (end - start <= 2){int min_val = abs(num - arr[start]);for (int i=start; i <= end; i++)min_val = min(abs(num - arr[i]), min_val);for (int i=start; i <= end; i++)if min_val == abs(num - arr[i])return i;}// 02. check the mid value then exclude the wrong sideint mid = (end - start)/2;if (arr[mid] < num)return solve(arr, num, mid + 1, end);elsereturn solve(arr, num, start, mid);}