Short Java Code, O(n), one pass


  • 0
    F

    Share my short Java code.

        public List<Integer> findClosestElements(List<Integer> arr, int k, int x) {
            LinkedList<Integer> res = new LinkedList<>();
            for (Integer i : arr) {
                if (res.size() < k) res.add(i);
                else {
                    if (Math.abs(res.peek() - x) > Math.abs(i - x)) {
                        res.removeFirst();
                        res.add(i);
                    }
                }
            }
            return res;
        }
    

Log in to reply
 

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