int mergeSort(vector<int>& nums, int left, int right) {
if (left >= right) return 0;
int mid = left + (right - left) / 2;
// 分治递归
long long count = mergeSort(nums, left, mid) + mergeSort(nums, mid + 1, right);
// 归并合并
vector<int> temp(right - left + 1);
int i = left, j = mid + 1, k = 0;
while (i <= mid && j <= right) {
if (nums[i] <= nums[j])
temp[k++] = nums[i++];
else {
temp[k++] = nums[j++];
count += mid - i + 1; // 统计逆序对数量
}
}
while (i <= mid)
temp[k++] = nums[i++];
while (j <= right)
temp[k++] = nums[j++];
for (int p = 0; p < k; ++p)
nums[left + p] = temp[p];
return count;
}