Monday, August 11, 2014

Given a sorted array arr[] and a value X, find the k closest elements to X in arr[]. Examples: Input: K = 4, X = 35 arr[] = {12, 16, 22, 30, 35, 39, 42, 45, 48, 50, 53, 55, 56} Output: 30 39 42 45


import java.util.Arrays;

/**
 * Created by Arun on 8/11/14.
 */
public class ClosestArray {
    private static int[] getClosest(int num, int element, int arr[]){
        int elementIndex = -1;
        int closeArray [] = new int[num];
        for(int i=0;i<arr.length;i++) {
            if(arr[i]==element){
                elementIndex = i;
            }
        }
        for(int i=0, j=elementIndex-1, k=elementIndex+1;i<num;i++){
            int diff1 = element-arr[j];
            int diff2  = arr[k]-element;
            if(diff1<diff2){
                closeArray[i]=arr[j];
                j--;
            }
            else if(diff1>diff2) {
                closeArray[i]=arr[k];
                k++;
            }
            else{
                closeArray[i]=arr[j];
                if(i<num){
                    i++;
                    closeArray[i]=arr[k];
                    j--;
                    k++;
                }
                else {
                    break;
                }
            }
        }
        return closeArray;
    }

    public static void main(String args[]) {
        int arr[] = {12, 16, 22, 31, 35, 39, 42, 45, 48, 50, 53, 55, 56};
        getClosest(4, 35, arr);
    }
}

No comments:

Post a Comment