Find the nearest/closest value in a sorted List

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

    It seems like the easiest way is simply to iterate over the sorted list, checking each item.

    List<Integer> ints = new ArrayList<>();
    ints.add(1);
    ints.add(3);
    ints.add(6);
    ints.add(7);
    
    Collections.sort(ints);
    
    int target = 4;
    int nearest = 0;
    
    for (int i : ints)
    {
        if (i <= target) {
            nearest = i;
        }
    }
    
    System.out.println(nearest);
    

    This outputs the largest item in the list which is less than or equal to the target.

    0 讨论(0)
  • 2020-12-05 11:50

    You need Array.binarySearch, docs.

    Returns: index of the search key, if it is contained in the array; otherwise, (-(insertion point) - 1). The insertion point is defined as the point at which the key would be inserted into the array: the index of the first element greater than the key, or a.length if all elements in the array are less than the specified key.

    0 讨论(0)
提交回复
热议问题