We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
public static List closestNumbers(List arr) {
// Write your code here
// 5,4,3,2
List<List<Integer>> list = new ArrayList<>(arr.size() - 1);
for (int i = 0; i < arr.size() - 1; i++) {
list.add(new ArrayList<>());
}
arr = arr.stream().sorted().collect(Collectors.toList());
for (int i = 0; i < arr.size() - 1; i++) {
list.get(i).add(arr.get(i));
list.get(i).add(arr.get(i + 1));
}
List<Integer> ind = new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
ind.add(list.get(i).get(1) - list.get(i).get(0));
}
int smaller = ind.stream().min(Comparator.naturalOrder()).orElse(0);
List<Integer> res = new ArrayList<>();
for (int i = 0; i < ind.size(); i++) {
if (ind.get(i) == smaller) {
list.get(i).forEach(f -> res.add(f));
}
}
// System.out.println(res);
return res;
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Closest Numbers
You are viewing a single comment's thread. Return to all comments →
public static List closestNumbers(List arr) { // Write your code here