Saturday, June 18, 2016

#codingexercise
Given a sorted array of number , value K and value X, find the K nearest number to the value
Example: Input 12 16 22 30 35 39 42 45 48 50 53 55 56 K = 4 X = 35
Output 22 30 39 42
List<int> GetKNearest(List<int>sorted, int X, int K)
{
var ret = new List<int>();
var index = find(sorted, X, 0, sorted.Count -1);
If ( index == - 1) return null;
int start = index-1;
int end = index +1;
for (int i = 0; i <k; i++)
{
if (start >=0 && end < sorted.Count){
    if (sorted[index]-sorted[start] < sorted[end]-sorted[index])
    {
         ret.Add(sorted[start]);
         start--;
    }else{
         ret.Add(sorted[end]);
         end++;
    }
}else if (start >= 0){
    ret.Add(sorted[start])
    start--;
}else if (end < sorted.Count){
    ret.Add(sorted[end])
    end++;
}
return ret;
}
int find(List<int> sorted, int X, int start, int end)
{
If (end < start) return - 1;
int mid = (start + end)/2
if (sorted[mid] == X) return mid;
if (sorted[mid] < X)
   return find(sorted, X, mid+1, end);
else
   return find(sorted, X, start, mid-1);
}

No comments:

Post a Comment