我都天真傻逼超时代码:
class Solution {
public:
int InversePairs(vector<int> data) {
int count = 0;
for(int i = 0; i < data.size(); i++) {
for(int j = 0; j < i; j++){
if(data[j] > data[i]) count++;
if(count == 1000000007) count = 0;
}
}
return count;
}
};
归并排序思路,时间复杂度O(nlogn),空间复杂度O(n):
class Solution {
public:
int InversePairs(vector<int> data) {
int size = data.size();
if(size <= 1) return 0;
vector<int> temp(size); //额外需要的数组空间
int res = 0;
merge_(data, temp, 0, size-1, res);
return res;
}
//递归分块(二路归并)
void merge_(vector<int> &array, vector<int> &temp, int l, int r, int &res){
if(l >= r) return;
int mid = l + ((r - l)>>1);
merge_(array, temp, l, mid, res);
merge_(array, temp, mid+1, r, res);
merge_sort(array, temp, l, mid, r, res);
}
//两块有序块合并成一个有序块
void merge_sort(vector<int> &array, vector<int> &temp, int l, int mid, int r, int &res){
int i = l, j = mid + 1, k = 0;
while(i <= mid && j <= r){
if(array[i] > array[j]) {
temp[k++] = array[j++];
res += mid-i+1; //统计逆序对
res %= 1000000007;
}
else {
temp[k++] = array[i++];
}
}
while(i <= mid) {
temp[k++] = array[i++];
}
while(j <= r) {
temp[k++] = array[j++];
}
for(i = l, k = 0; i <= r; i++, k++) {
array[i] = temp[k];
}
}
};