Finding closest number in an array

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

    Pseudocode to return list of closest integers.

    myList = new ArrayList();          
    
    if(array.length==0) return myList; 
    
    myList.add(array[0]);
    
    int closestDifference = abs(array[0]-numberToFind);
    
    for (int i = 1; i < array.length; i++) {
    
     int currentDifference= abs(array[i]-numberToFind);
    
      if (currentDifference < closestDifference) {
    
        myList.clear();
    
        myList.add(array[i]);
    
             closestDifference = currentDifference;
    
      } else {
    
        if(currentDifference==closestDifference) {
    
            if( myList.get(0) !=array[i]) && (myList.size() < 2) {
    
                myList.add(array[i]);
    
            }
                }
    
           }
    
    }
    
    return myList;
    

提交回复
热议问题