Simple O(n) Java solution using a Queue


  • 0
    C

    This solution takes advantage of the requirement that we always prefer the smallest numbers.

    public List<Integer> findClosestElements(List<Integer> arr, int k, int x) {
            Queue<Integer> q = new LinkedList<Integer>();
            for(Integer i : arr) {
                if(q.size() < k) q.offer(i);
                else if(Math.abs(q.peek() - x) > Math.abs(i - x)) {
                    q.offer(i);
                    q.poll();
                }
            }
            return new ArrayList<Integer>(q);
        }
    

Log in to reply
 

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