Find all differences in an array in O(n)

前端 未结 7 1043
没有蜡笔的小新
没有蜡笔的小新 2020-12-30 05:39

Question: Given a sorted array A find all possible difference of elements from A.

My solution:

for (int i=0; i

        
7条回答
  •  猫巷女王i
    2020-12-30 06:16

    You can get another counter-example by assuming the array contents are random integers before sorting. Then the chance that two differences, Ai - Aj vs Ak - Al, or even Ai - Aj vs Aj - Ak, are the same is too small for there to be only O(n) distinct differences Ai - Aj.

    Given that, the question to your interviewer is to explain the special circumstances that allow an O(n) solution. One possibility is that the array values are all numbers in the range 0..n, because in this case the maximum absolute difference is only n.

    I can do this in O(n lg n) but not O(n). Represent the array contents by an array of size n+1 with element i set to 1 where there is a value i in the array. Then use FFT to convolve the array with itself - there is a difference Ai - Aj = k where the kth element of the convolution is non-zero.

提交回复
热议问题