Finding closest number in an array

前端 未结 11 917
萌比男神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:45

    // paulmurray's answer to your question is really the best :
    
    // The least square solution is way more elegant, 
    // here is a test code where numbertoLookFor
    // is zero, if you want to try ...
    
    import java.util.* ;
    
    public class main {
        public static void main(String[] args) 
        {
            int[] somenumbers = {-2,3,6,1,5,5,-1} ;
            ArrayList l = new ArrayList(10) ;
            for(int i=0 ; i()
                    {
                        public int compare(Integer n1, Integer n2)
                        {
                            return n1*n1 - n2*n2 ;
                        }
                    }
            ) ;
            Integer first = l.get(0) ;
            System.out.println("nearest number is " + first) ;  
        }
    }
    

提交回复
热议问题