You are viewing a single comment's thread. Return to all comments →
TimeComplexity = O(n)
SpaceComplexity = O(n)
n : the list size of input arr
public static List<Integer> closestNumbers(List<Integer> arr) { if (arr == null || arr.isEmpty()) return new ArrayList<>(); if (arr.size() == 1) return arr; Collections.sort(arr); Map<Integer, List<Integer>> map = new HashMap<>(); int min = Integer.MAX_VALUE, diff = 0; for (int i=1;i<arr.size();i++) { diff = arr.get(i) - arr.get(i-1); min = Math.min(min, diff); if (!map.containsKey(diff)) map.put(diff, new ArrayList<>()); map.get(diff).add(arr.get(i-1)); map.get(diff).add(arr.get(i)); } return map.get(min); }
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 →
JAVA Solution
TimeComplexity = O(n)
SpaceComplexity = O(n)
n : the list size of input arr