I've seen this interesting question, and wonder if there are more ways to approach it:
Given a permutation of numbers from 1 to n, count the number of quadruples indices (i,j,k,l) such that i<j<k<l and A[i]<A[k]<A[j]<A[l]
eg
Input: [1,3,2,6,5,4]
Output: 1 (1,3,2,6)
Desired algorithm is O(n^2)
Approach: I've tried to solve it using stack, in a similiar manner to Leetcode 132 pattern - but it seems to fail.
def get_smaller_before(A):
smaller_before = [0] * len(A)
for i in range(len(A)):
for j in range(i):
if A[j] < A[i]:
smaller_before[i] += 1
return smaller_before
def get_larger_after(A):
larger_after = [0] * len(A)
for i in range(len(A)):
for j in range(i+1, len(A)):
if A[i] < A[j]:
larger_after[i] += 1
return larger_after
def countQuadrples(nums):
if not nums:
return False
smaller_before = get_smaller_before(nums)
larger_after = get_larger_after(nums)
counter = 0
stack = []
for j in reversed(range(1, len(nums))):
# i < j < k < l
# smaller_before < nums[k] < nums[j] < larger_after
while stack and nums[stack[-1]] < nums[j]:
counter += smaller_before[j] * larger_after[stack[-1]]
stack.pop()
stack.append(j)
return counter
Does anyone has a better idea?
What you need is some sort of 2-dimensional tree that allows you to quickly answer the question "How many points after k
have value bigger than A[j]
," and the question "How many points before j have value less than A[k]
?" These will usually be time O(n log(n))
to build and those queries should run in time something like O(log(n)^2))
.
A number of such data structures exist. One option is a variant on a Quadtree . You you turn each array element into a point with x-coordinate the position in the array and y-coordinate being its value. And your queries are just counting how many elements are in a box.
And now you can do a double loop over all j, k
and count how many zig-zag quadruples have those as the inner pair.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.