Find the nearest/closest value in a sorted List

前端 未结 8 1633
我寻月下人不归
我寻月下人不归 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:32

    If the array is sorted you can do a modified binary search in O( log n ) :

        public static int search(int value, int[] a) {
    
            if(value < a[0]) {
                return a[0];
            }
            if(value > a[a.length-1]) {
                return a[a.length-1];
            }
    
            int lo = 0;
            int hi = a.length - 1;
    
            while (lo <= hi) {
                int mid = (hi + lo) / 2;
    
                if (value < a[mid]) {
                    hi = mid - 1;
                } else if (value > a[mid]) {
                    lo = mid + 1;
                } else {
                    return a[mid];
                }
            }
            // lo == hi + 1
            return (a[lo] - value) < (value - a[hi]) ? a[lo] : a[hi];
        }
    

提交回复
热议问题