问题
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:
Set
b[i] = a[i] - i
The problem becomes:find (i,j), i<j, s.t. b[i] + b[j] = 0
Complexity: O(n)Create objects
c[i] = (b[i],i)
, a struct for example, in a std::vector (or std::array)
Complexity: O(n)Sort the
c[i]
pairs according tob
values -> getd[j] = (v[j], i[j])
, sorted array
Complexity: O(nlogn)Find all pairs
j,k
such thatv[j] = -v[k]
Complexity: the array being sorted, should be O(n)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