void merge(vector<int> arr, int l, int m, int r,int &count)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
/* create temp arrays */
vector<int> L, R;
/* Copy data to temp arrays L[] and R[] */
for (i = 0; i < n1; i++)
L.push_back(arr[l+i]);
for (j = 0; j < n2; j++)
R.push_back(arr[m+1+j]);
/* Merge the temp arrays back into arr[l..r]*/
i = 0; // Initial index of first subarray
j = 0; // Initial index of second subarray
k = l; // Initial index of merged subarray
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
count+=(n1-i);
j++;
}
k++;
}
/* Copy the remaining elements of L[], if there
are any */
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
/* Copy the remaining elements of R[], if there
are any */
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
/* l is for left index and r is right index of the
sub-array of arr to be sorted */
void mergeSort(vector<int> arr, int l, int r,int &count)
{
if (l < r)
{
// Same as (l+r)/2, but avoids overflow for
// large l and h
int m = l+(r-l)/2;
// Sort first and second halves
mergeSort(arr, l, m,count);
mergeSort(arr, m+1, r,count);
merge(arr, l, m, r,count);
}
}
int Solution::countInversions(vector<int> &A) {
int count = 0;
mergeSort(A,0,A.size()-1,count);
return count;
}
这是我的计数反转次数的代码。我也尽早解决了这个问题,所以我对实现的逻辑很有信心,我不知道为什么它在面试“比特测试用例”时没有通过某些测试用例。任何帮助将不胜感激!谢谢。
您的提交因以下输入而失败:
A : [ 84, 2, 37, 3, 67, 82, 19, 97, 91, 63, 27, 6, 13, 90, 63, 89, 100, 60, 47, 96, 54, 26, 64, 50, 71, 16, 6, 40, 84, 93, 67, 85, 16, 22, 60 ]
您的函数返回了以下内容:
372
期望的返回值:
290
答案 0 :(得分:0)
您正在计算递归的每个级别的反转;这个问题(显然)只对输入数组中的反转感兴趣。
如果将您对反转的定义应用于输入数组,则会得到预期的返回值。