我最近在编程竞赛中没能成功解决以下问题 -
给定一个包含 n 个值的数组 ar[]
,你需要找到包含大于或等于 k 个逆序对的子数组数量。
数组中逆序对的数量被定义为索引对 (i,j) 的数量,满足
1 <= i < j <= n and ar[i] > ar[j].
预计最坏情况下的时间复杂度为 O(nlogn)
。
我最近在编程竞赛中没能成功解决以下问题 -
给定一个包含 n 个值的数组 ar[]
,你需要找到包含大于或等于 k 个逆序对的子数组数量。
数组中逆序对的数量被定义为索引对 (i,j) 的数量,满足
1 <= i < j <= n and ar[i] > ar[j].
预计最坏情况下的时间复杂度为 O(nlogn)
。
let total=0;
let i,j=1,1;
while(i<=N)
{
while (j<i || inversions in ar[i]...ar[j] < K)
{
++j;
if (j>N)
{
return total; //out of subarrays
}
}
// (i,j) is now a minimal subarray
total+=N+1-j
++i; //next start position
//now, IF (i,j) has enough inversions, then it is STILL
//minimal, because otherwise the previous subarray would not have
//been minimal either
}
ar[i]...ar[j]
中的反转进行检查,每次迭代的成本最多为 O(log N)。