Find all differences in an array in O(n)

前端 未结 7 991
没有蜡笔的小新
没有蜡笔的小新 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条回答
  • 2020-12-30 06:20

    A first thought is that you aren't using the fact that the array is sorted. Let's assume it's in increasing order (decreasing can be handled analogously).

    We can also use the fact that the differences telescope (i>j):

    a_i - a_j = (a_i - a_(i-1)) + (a_(i-1) - a_(i-2)) + ... + (a_(j+1) - a_j)
    

    Now build a new sequence, call it s, that has the simple difference, meaning (a_i - a_(i-1)). This takes only one pass (O(n)) to do, and you may as well skip over repeats, meaning skip a_i if a_i = a_(i+1).

    All possible differences a_i-a_j with i>j are of the form s_i + s_(i+1) + ... + s_(j+1). So maybe if you count that as having found them, then you did it in O(n) time. To print them, however, may take as many as n(n-1)/2 calls, and that's definitely O(n^2).

    0 讨论(0)
提交回复
热议问题