Find total number of (i,j) pairs in an array such that i<j and a[i]+a[j]=i+j. [closed]

烈酒焚心 提交于 2019-12-13 11:31:42

问题


I have a naive solution which uses two loops, but I want to improve the time complexity as O(nlogn). Any better approach available?

The array is unsorted and can have negative values too.

Sample Test Case: Array: 1 0 3 2

Output: 4

Explanation: Indices - (0,1), (0,3), (1,2), (2,3) are the pairs which satisfy the given constraints.


回答1:


Problem: find (i,j), i<j, s.t. a[i] + a[j] = i + j

I propose the following approach:

  1. Set b[i] = a[i] - i
    The problem becomes: find (i,j), i<j, s.t. b[i] + b[j] = 0
    Complexity: O(n)

  2. Create objects c[i] = (b[i],i), a struct for example, in a std::vector (or std::array)
    Complexity: O(n)

  3. Sort the c[i] pairs according to b values -> get d[j] = (v[j], i[j]) , sorted array
    Complexity: O(nlogn)

  4. Find all pairs j,k such that v[j] = -v[k]
    Complexity: the array being sorted, should be O(n)

  5. keep the cases i[j] < i[k]
    Complexity: O(n)



来源:https://stackoverflow.com/questions/53343473/find-total-number-of-i-j-pairs-in-an-array-such-that-ij-and-aiaj-ij

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!