Simple Approach using Priority Queue
class Pair implements Comparable{\n        int gap;\n        int val;\n        Pair()\n        {\n            \n        }\n        Pair(int val,int gap)\n      
class Pair implements Comparable<Pair>{\n        int gap;\n        int val;\n        Pair()\n        {\n            \n        }\n        Pair(int val,int gap)\n        {\n            this.gap = gap;\n            this.val =val;\n        }\n       public  int compareTo(Pair o)\n        {\n            if(this.gap == o.gap)\n                return this.val -o.val;\n            else\n                return this.gap -o.gap;\n        }\n        \n    }\n    public List<Integer> findClosestElements(int[] arr, int k, int x) {\n        ArrayList<Integer> al = new ArrayList<>();\n        PriorityQueue<Pair> pq = new PriorityQueue<>(Collections.reverseOrder());\n        \n        for(int i =0;i<arr.length;i++)\n        {\n            if(pq.size()<k)\n                pq.add(new Pair(arr[i],Math.abs(arr[i]-x)));\n\n            else{\n                if(pq.peek().gap > Math.abs(arr[i]-x))\n                {\n                    pq.remove();\n                    pq.add(new Pair(arr[i],Math.abs(arr[i]-x)));\n                }\n            }\n            \n        }\n        while(pq.size()>0)\n        {\n            Pair p = pq.remove();\n            al.add(p.val);\n        }\n        \n        Collections.sort(al);\n        return al;\n        \n    }\n}
[]