Find Nearest element of Given Number
import java.util.*;
public class FindNearestElementInArrayForGivenNumber {
public static int findNearestElement(int[] a,int number){
Map<Integer,Integer> params =new HashMap<>();
for(int i=0;i<a.length;i++){
params.put(Math.abs(a[i]-number),a[i]);
}
List<Integer> keySetList = new ArrayList<>(params.keySet());
Collections.sort(keySetList);
return params.get(keySetList.get(0));
}
public static void main(String[] args) {
int[] e = {5,10,15,20};
System.out.println("Nearest element:"+
findNearestElement(e,11));
}
}
Comments
Post a Comment