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<>());
                map.get(abs).add(a);
            }
            for (Map.Entry<Integer, List<Integer>> e : map.entrySet()) {
                for (int i : e.getValue()) {
                    result.add(i);
                    if (result.size() == k) break;
                }
                if (result.size() == k) break;
            }
            Collections.sort(result);
            return result;
        }
    

  • 0
    T

    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.