题解 | #数组中的逆序对#
数组中的逆序对
http://www.nowcoder.com/practice/96bd6684e04a44eb80e6a68efc0ec6c5
class Solution {
public:
void merge_sort(vector<int>& vec, int l, int r, int& res) {
if(l >= r)
return;
int mid = (l + r) / 2;
merge_sort(vec, l, mid, res);
merge_sort(vec, mid + 1, r, res);
int i = l, j = mid + 1, k = 0;
vector<int> temp(r-l+1);
while(i <= mid && j <= r) {
if(vec[i] <= vec[j]) {
temp[k++] = vec[i++];
}else {
res += (mid - i + 1);
res = res % 1000000007;
temp[k++] = vec[j++];
}
}
while(i <= mid) {
temp[k++] = vec[i++];
}
while(j <= r) {
temp[k++] = vec[j++];
}
i = l, k = 0;
while(l <= r) {
vec[l++] = temp[k++];
}
return;
}
int InversePairs(vector<int> data) {
int res = 0;
int n = data.size();
if( n < 2)
return res;
merge_sort(data, 0, n - 1, res);
return res;
}
};