easy java

  • 8
        public List<Integer> findClosestElements(List<Integer> arr, int k, int x) {
            List<Integer> result = new LinkedList<>();
            TreeMap<Integer, List<Integer>> map = new TreeMap<>();
            for (int a : arr) {
                int abs = Math.abs(a - x);
                if (!map.containsKey(abs)) map.put(abs, new LinkedList<>());
            for (Map.Entry<Integer, List<Integer>> e : map.entrySet()) {
                for (int i : e.getValue()) {
                    if (result.size() == k) break;
                if (result.size() == k) break;
            return result;

  • 0

    Just curious why you use TreeMap instead of hashmap? Is it because treemap is sorted by keys?

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.