We receive a sorted array, value V, and lots K. The value represents the quantity that can happen in the array, but it isn't mandatory. We are anticipated to discover a group of size K, which has the elements from the array, that will be the closest to the value.
The answer uses the famous binary search algorithm. First of all, we find the value V itself, or the closest to V, in the array. The second option, we obtain just because of this of a normal binary search, that results in the positioning of the factor if it is present, or the positioning where it could show up. Let's call this position P. We realize that the component at position P, will be contained in the result arranged. Now we have to consider the elements on the still left and the right side of P. As the array is sorted, the closest component to the main one on the positioning P will place on the positioning P-1 or P+1. We choose the one which is nearer, and iteratively process until we complete the set in place to the expected size. A good example code:
 |
No comments:
Post a Comment