in reply to Re: Find a number in a list closest to a target
in thread Find a number in a list closest to a target

This may or may not be a wholly useful thing to do, depending on some stuff that he didn't state in his problem. It wasn't clear from his description whether or not he would be repeatedly doing searches on the same list, or if he'd be getting a fresh list every time. If he uses the naive method of traversing the whole n element array, this will yield him O(n) for one search, and O(m*n) were he to perform this search m times. With your strategy, in the case of a single search he'd get O(n*lg(n)) (unnecessary overhead because we're doing pre-processing then throwing it away), but in the case of m searches we'd have O(m*lg(n)) + O(n*lg(n)) = O((m+n)*lg(n)) which we can simplify further if we know the relative sizes of m and n. Thus, your idea is fantastic if he meant he'd be repeatedly searching on the same list, but he wasn't clear whether that was the case, so it might turn out to be an investment of pre-computation in a problem that doesn't in fact exist.
  • Comment on Re: Re: Find a number in a list closest to a target