Finding closest number in an array

前端 未结 11 909
萌比男神i
萌比男神i 2021-01-31 22:10

In an array first we have to find whether a desired number exists in that or not? If not then how will I find nearer number to the given desired number in Java?

11条回答
  •  野的像风
    2021-01-31 22:53

    //This will work

    public int nearest(int of, List in)
    {
    int min = Integer.MAX_VALUE;
    int closest = of;
    
    for (int v : in) 
    {
        final int diff = Math.abs(v - of);
    
        if (diff < min) 
        {
            min = diff;
            closest = v;
        }
    }
    return closest;
    }
    

提交回复
热议问题