Find the nearest/closest value in a sorted List

前端 未结 8 1658
我寻月下人不归
我寻月下人不归 2020-12-05 10:59

I was wondering if it is possible to find the closest element in a List for a element that is not there.

For example if we had the valu

8条回答
  •  醉酒成梦
    2020-12-05 11:24

    Another O(log n) easy to understand solution using binary search:

    public class Solution {
        static int findClosest(int arr[], int n, int target)
        {
            int l=0, h=n-1, diff=Integer.MAX_VALUE, val=arr[0];
            while(l<=h)
            {
                int mid=l+(h-l)/2;
                if(Math.abs(target-arr[mid])

提交回复
热议问题