Find K Closest Elements

https://www.lintcode.com/zh-cn/problem/find-k-closest-elements/

import java.util.Arrays;

public class Solution {
    /**
     * @param A: an integer array
     * @param target: An integer
     * @param k: An integer
     * @return: an integer array
     */
    public int[] kClosestNumbers(int[] A, int target, int k) {
        // write your code here
        int i = Arrays.binarySearch(A, target);
        if (i < 0) {
            i = -i - 1;
        }
        int[] res = new int[k];
        int bigger = i;
        int smaller = i - 1;
        for (int j = 0; j < res.length; j++) {
            if (smaller < 0) {
                res[j] = A[bigger];
                bigger++;
            } else if (bigger >= A.length) {
                res[j] = A[smaller];
                smaller--;
            } else {
                if (target - A[smaller] <= A[bigger] - target) {
                    res[j] = A[smaller];
                    smaller--;
                } else {
                    res[j] = A[bigger];
                    bigger++;
                }
            }

        }
        return res;
    }
}

你可能感兴趣的:(Find K Closest Elements)