给定一个包含n个元素的未排序数组,如何计算数组中出现次数,i < j < k
和a[i] < a[j] > a[k]
时间复杂度O(n log n)
。如果可以提高时间复杂度,请告诉我。
我推出了时间复杂度O(n^3)
的算法,它处理大的n值时速度太慢。
count = 0; // count for number of tuples following above condition
for(i = 0;i < n; i++)
for(j = i + 1;j < n; j++)
for(k = j + 1;k < n; k++)
if(a[i] < a[j] && a[j] > a[k])
count++;
for example we have an array [1, 2, 3, 1].
Now such occurrences are in index form(0 - based indexing)
[0 1 3]
[0 2 3]
[1 2 3].
答案 0 :(得分:1)
执行在线算法,将整数添加到集合中并二进制搜索小于当前整数的整数数量A[j]
在正常方向做一次,反向做一次,这样对于每个A[j]
,你可以存储整数&lt;位于A[j]
之前/之后的j
。
答案是所有j
Set<int> st, reverse_st;
int arr[N], reverse_arr[N];
int A[N], ans = 0;
FOR j = 0 to N-1
arr[j] = # of element in st < A[j], using binary search // O(lg N)
Insert A[j] into st // O(lg N)
FOR j = N-1 to 0
reverse_arr[j] = # of element in reverse_st < A[j], using binary search
Insert A[j] into reverse_st
FOR i = 0 to N-1
ans += arr[i] * reverse_arr[i]
Output ans
&#13;
使用您的示例A = [1,2,3,1]
arr = [0,1,2,0],reverse_arr = [0,1,1,0]
ans = 1 * 1 + 2 * 1 = 3