Is it possible to find two numbers whose difference is minimum in O(n) time

后端 未结 8 700
日久生厌
日久生厌 2020-12-04 20:05

Given an unsorted integer array, and without making any assumptions on the numbers in the array:
Is it possible to find two numbers whose difference is minimum i

8条回答
  •  独厮守ぢ
    2020-12-04 20:23

    I think it is possible. The secret is that you don't actually have to sort the list, you just need to create a tally of which numbers exist. This may count as "making an assumption" from an algorithmic perspective, but not from a practical perspective. We know the ints are bounded by a min and a max.

    So, create an array of 2 bit elements, 1 pair for each int from INT_MIN to INT_MAX inclusive, set all of them to 00.

    Iterate through the entire list of numbers. For each number in the list, if the corresponding 2 bits are 00 set them to 01. If they're 01 set them to 10. Otherwise ignore. This is obviously O(n).

    Next, if any of the 2 bits is set to 10, that is your answer. The minimum distance is 0 because the list contains a repeated number. If not, scan through the list and find the minimum distance. Many people have already pointed out there are simple O(n) algorithms for this.

    So O(n) + O(n) = O(n).

    Edit: responding to comments.

    Interesting points. I think you could achieve the same results without making any assumptions by finding the min/max of the list first and using a sparse array ranging from min to max to hold the data. Takes care of the INT_MIN/MAX assumption, the space complexity and the O(m) time complexity of scanning the array.

提交回复
热议问题